1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
use std::ops::Add;
use std::fmt;

#[derive(PartialEq, Debug, Clone)]
pub struct Sandpile {
    cols: i32,
    rows: i32,
    data: Vec<Vec<i32>>,
}

impl Sandpile {
    pub fn new(cols: i32, rows: i32, data: Option<Vec<i32>>) -> Sandpile {
        match data {
            None => {
                let temp_data: Vec<Vec<i32>> = vec![vec![0; cols as usize]; rows as usize];
                Sandpile {
                    rows: rows,
                    cols: cols,
                    data: temp_data
                }
            },
            Some(x) => {
                if x.len() != (cols*rows) as usize {
                    panic!("Data does not match Sandpile dimensions.");
                } else {
                    let mut temp_data: Vec<Vec<i32>> = vec![vec![0; cols as usize]; rows as usize];
                    let mut counter: usize = 0;
                    for i in 0..rows as usize {
                        for j in 0..cols as usize {
                            temp_data[i][j] = x[counter];
                            counter += 1;
                        }
                    }

                    let mut ret = Sandpile {
                        rows: rows,
                        cols: cols,
                        data: temp_data
                    };

                    ret = ret.stabilize();

                    ret
                }
            }
        }
    }
    
    pub fn stabilize(mut self) -> Self {
        let mut job_queue = self.get_job_queue();
        
        while !job_queue.is_empty() {
            self = self.topple_pass(job_queue);
            job_queue = self.get_job_queue();
        }
        self
    }

    fn is_add_compatible(&self, other: &Self) -> bool {
        if self.rows == other.rows && self.cols == other.cols {
            true
        } else {
            false
        }
    }

    fn topple_pass(mut self, job_queue: Vec<(usize, usize)>) -> Self {
        let y: usize = (self.cols - 1) as usize;
        let x: usize = (self.rows - 1) as usize;

        for (i, j) in job_queue {
            self.data[i][j] = self.data[i][j] - 4;
            if i == 0 && j == 0 {
                // Left corner
                self.data[0][1] += 1;
                self.data[1][0] += 1;
            } else if i == 0 && j == y {
                // Right corner
                self.data[0][j-1] += 1;
                self.data[1][j] += 1;
            } else if i == x && j == 0 {
                // Bottom left
                self.data[i-1][0] += 1;
                self.data[i][1] += 1;
            } else if i == x && j == y {
                // Bottom right
                self.data[i-1][j] += 1;
                self.data[i][j-1] += 1;
            } else if i == 0 {
                // First row
                self.data[0][j-1] += 1;
                self.data[0][j+1] += 1;
                self.data[1][j] += 1;
            } else if j == 0 {
                // First collumn
                self.data[i-1][0] += 1;
                self.data[i+1][0] += 1;
                self.data[i][1] += 1;
            } else if i == x {
                // Last row
                self.data[i][j-1] += 1;
                self.data[i][j+1] += 1;
                self.data[i-1][j] += 1;
            } else if j == y {
                // Last collumn
                self.data[i-1][j] += 1;
                self.data[i+1][j] += 1;
                self.data[i][j-1] += 1;
            } else {
                self.data[i-1][j] += 1;
                self.data[i+1][j] += 1;
                self.data[i][j-1] += 1;
                self.data[i][j+1] += 1;
            }
        }
        
        self
    }

    fn get_job_queue(&self) -> Vec<(usize, usize)> {
        let mut job_queue: Vec<(usize, usize)> = Vec::new();

        for i in 0..self.rows as usize {
            for j in 0..self.cols as usize {
                if self.data[i][j] > 3 {
                    job_queue.push((i,j));
                }
            }
        }

        job_queue
    }

}

impl Add for Sandpile {
    type Output = Sandpile;

    fn add(self, other: Sandpile) -> Sandpile {
        if self.is_add_compatible(&other) {
            let mut a = Sandpile::new(self.rows, self.cols, None);
            
            for i in 0..self.rows as usize {
                for j in 0..self.cols as usize {
                    a.data[i][j] = self.data[i][j] + other.data[i][j];
                }
            }

            a.stabilize()
        } else {
            panic!("The two sandpiles are not compatible for addition!");
        }
    }
}

impl fmt::Display for Sandpile {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for i in 0..self.rows as usize {
            for j in 0..self.cols as usize {
                write!(f, "{} | ", self.data[i][j]).unwrap();
            }
            write!(f, "\n").unwrap();
        }
        write!(f, "")
    }
}

#[cfg(test)]
mod tests {
    use super::Sandpile;

    #[test]
    fn test_equality() {
        let a = Sandpile::new(3, 3, None);
        let b = Sandpile::new(3, 3, None);

        assert_eq!(a, b)
    }

    #[test]
    fn test_data_initialization() {
        let a = Sandpile {
            rows: 3,
            cols: 3,
            data: vec![vec![1,1,1], vec![1,2,1], vec![2,2,2]]
        };

       let b = Sandpile::new(3, 3, Some(vec![1,1,1,1,2,1,2,2,2]));

       assert_eq!(a,b)
    }

    #[test]
    fn stabilization_test_1() {
        let a = Sandpile {
            rows: 3,
            cols: 3,
            data: vec![vec![4,4,4], vec![0,0,0], vec![1,1,1]]
        };

        let b = Sandpile {
            rows: 3,
            cols: 3,
            data: vec![vec![1,2,1], vec![1,1,1], vec![1,1,1]]
        };

        assert_eq!(a.stabilize(), b);
    }

    #[test]
    fn stabilization_test_2() {
         let a = Sandpile {
            rows: 3,
            cols: 3,
            data: vec![vec![4,4,4], vec![4,4,4], vec![2,2,2]]
        };

        let b = Sandpile {
            rows: 3,
            cols: 3,
            data: vec![vec![2,3,2], vec![2,3,2], vec![3,3,3]]
        };

        assert_eq!(a.stabilize(), b);
    }

    #[test]
    fn addition_test() {
        let a = Sandpile::new(3, 3, Some(vec![2, 1, 2, 1, 0, 1, 2, 1, 2]));
        let b = Sandpile::new(3, 3, Some(vec![2, 1, 2, 1, 0, 1, 2, 1, 2]));

        let d = a.clone();

        let c = a + b;

        assert_eq!(c, d)
    }
}