|
| 1 | +pub fn run(input: Vec<String>) { |
| 2 | + let part1 = solve(&input, 100, false); |
| 3 | + println!("part 1: {}", part1); |
| 4 | + assert_eq!(part1, 1061); |
| 5 | + |
| 6 | + let part2 = solve(&input, 100, true); |
| 7 | + println!("part 2: {}", part2); |
| 8 | + assert_eq!(part2, 1006); |
| 9 | +} |
| 10 | + |
| 11 | +fn solve(input: &Vec<String>, iterations: u64, sticky: bool) -> u64 { |
| 12 | + let mut grid = [[false; 100]; 100]; |
| 13 | + |
| 14 | + // process each line of input |
| 15 | + for (y, line) in input.iter().enumerate() { |
| 16 | + for (x, c) in line.chars().enumerate() { |
| 17 | + if c == '#' { |
| 18 | + grid[y][x] = true; |
| 19 | + } |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + // run Conway's game of life iterations number of times |
| 24 | + for _ in 0..iterations { |
| 25 | + // create a copy of the existing grid |
| 26 | + let mut grid2 = [[false; 100]; 100]; |
| 27 | + for y in 0..100 { |
| 28 | + for x in 0..100 { |
| 29 | + grid2[y][x] = grid[y][x]; |
| 30 | + } |
| 31 | + } |
| 32 | + |
| 33 | + for y in 0..100 { |
| 34 | + for x in 0..100 { |
| 35 | + // count neighbors |
| 36 | + let mut c = 0; |
| 37 | + for dy in -1..2 { |
| 38 | + for dx in -1..2 { |
| 39 | + if (dx == 0) && (dy == 0) { |
| 40 | + continue; |
| 41 | + } |
| 42 | + if y + dy < 0 { |
| 43 | + continue; |
| 44 | + } |
| 45 | + if y + dy >= 100 { |
| 46 | + continue; |
| 47 | + } |
| 48 | + if x + dx < 0 { |
| 49 | + continue; |
| 50 | + } |
| 51 | + if x + dx >= 100 { |
| 52 | + continue; |
| 53 | + } |
| 54 | + |
| 55 | + if grid2[(y + dy) as usize][(x + dx) as usize] { |
| 56 | + c += 1; |
| 57 | + } |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + // change state on grid but by looking up in grid2 |
| 62 | + if grid2[y as usize][x as usize] { |
| 63 | + grid[y as usize][x as usize] = (c == 2) || (c == 3); |
| 64 | + } else { |
| 65 | + grid[y as usize][x as usize] = c == 3; |
| 66 | + } |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + if sticky { |
| 71 | + grid[0][0] = true; |
| 72 | + grid[99][0] = true; |
| 73 | + grid[0][99] = true; |
| 74 | + grid[99][99] = true; |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + // count how many lights are lit |
| 79 | + let mut lit = 0; |
| 80 | + for x in grid.iter() { |
| 81 | + for y in x.iter() { |
| 82 | + if *y { |
| 83 | + lit += 1; |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | + return lit; |
| 88 | +} |
0 commit comments