summaryrefslogtreecommitdiff
path: root/rotting-oranges/src/main_2.rs
diff options
context:
space:
mode:
Diffstat (limited to 'rotting-oranges/src/main_2.rs')
-rw-r--r--rotting-oranges/src/main_2.rs80
1 files changed, 80 insertions, 0 deletions
diff --git a/rotting-oranges/src/main_2.rs b/rotting-oranges/src/main_2.rs
new file mode 100644
index 0000000..6e806a7
--- /dev/null
+++ b/rotting-oranges/src/main_2.rs
@@ -0,0 +1,80 @@
+fn main() {
+ let tests: Vec<Vec<Vec<i32>>> = vec![
+ vec![
+ vec![2,1,1],
+ vec![1,1,0],
+ vec![0,1,1]
+ ],
+ vec![
+ vec![2,1,1],
+ vec![0,1,1],
+ vec![1,0,1]
+ ],
+ vec![
+ vec![0,2]
+ ],
+ vec![
+ vec![1,2]
+ ]
+ ];
+ let outputs = [4,-1,0,1];
+ for (n, test) in tests.iter().enumerate() {
+ let c: Vec<Vec<i32>> = test.to_vec();
+ let result = oranges_rotting(c);
+ println!("test {} result {} should be {}", n, result, outputs[n]);
+ }
+}
+
+
+fn oranges_rotting(grid: Vec<Vec<i32>>) -> i32 {
+ let mut grid1 = grid.clone();
+ let mut grid2 = grid1.clone();
+
+ let mut minutes: i32 = -1;
+ let mut some_fresh: bool = true;
+ let mut some_different: bool;
+ while some_fresh {
+ some_fresh = false;
+ some_different = false;
+
+ println!("Minute {}", minutes);
+
+ for (x, row) in grid1.iter().enumerate() {
+ for (y, col) in row.iter().enumerate() {
+ some_fresh |= *col == 1;
+ if *col != 2 {continue;}
+ let r: [i32; 3] = [-1,0,1];
+ for ix in r {
+ for iy in r {
+ if ix.abs() == iy.abs() {continue;}
+ let field: &mut i32 = &mut grid2[
+ (x as i32 + ix).clamp(0,grid.len() as i32 -1) as usize
+ ][
+ (y as i32 + iy).clamp(0,grid[0].len() as i32 -1) as usize
+ ];
+ if *field == 1 {
+ *field = 2;
+ }
+ }
+ }
+ }
+ println!("{:?} {:?}", row, grid2[x]);
+ }
+ for (x, row) in grid1.iter().enumerate() {
+ for (y, col) in row.iter().enumerate() {
+ some_different |= grid1[x][y] != grid2[x][y];
+ }
+ }
+
+ if !some_different && some_fresh {
+ println!("impossible");
+ return -1;
+ }
+
+ grid1 = grid2;
+ grid2 = grid1.clone();
+ minutes += 1;
+ }
+ return minutes;
+}
+