diff --git a/src/day7.rs b/src/day7.rs index 982ce4c..64150bf 100644 --- a/src/day7.rs +++ b/src/day7.rs @@ -1,6 +1,5 @@ use aoc_runner_derive::{aoc, aoc_generator}; use grid::{Coord2d, Grid}; -use itertools::Itertools; use std::str::FromStr; #[aoc_generator(day7)] @@ -25,34 +24,36 @@ fn part1(input: &Grid) -> u64 { #[aoc(day7, part2)] fn part2(input: &Grid) -> u64 { - let mut grid = Grid::same_shape(input, 0u64); - grid.set(&input.find(&b'S').unwrap(), 1); + let mut col_counts = vec![0; input.width()]; + col_counts[input.find(&b'S').unwrap().x as usize] = 1; // Start row is already set up - for y in 1..grid.height() { - let row_above = grid.row_iter(y as i64 - 1).unwrap().cloned().collect_vec(); - // for each column with non-zero counts in the row above get its column index and count - for (x, n) in row_above.into_iter().enumerate().filter(|(_i, n)| *n > 0) { + for y in 1..input.height() { + // for each column with non-zero counts + for x in 0..input.width() { + if col_counts[x] == 0 { + continue; + } match input.get(&(x, y)) { - None => panic!("How did we end up outside the grid?"), // if our current position is a caret, add that count to our neighbours Some(b'^') => { - grid.increment(&(x - 1, y), n); - grid.increment(&(x + 1, y), n); + for col in [x as i64 - 1, x as i64 + 1] + .into_iter() + .filter(|x| *x >= 0 && *x < input.width() as i64) + { + col_counts[col as usize] += col_counts[x]; + } + col_counts[x] = 0; } - // if our current position is a . add that count here - Some(b'.') => { - grid.increment(&(x, y), n); - } - _ => panic!(), + // if our current position is a . do nothing, it's already counted + Some(b'.') => continue, + Some(c) => panic!("unexpected character {c}"), + None => panic!("How did we end up outside the grid?"), } } } - grid.row(grid.height() as i64 - 1) - .unwrap() - .iter() - .sum::() + col_counts.iter().sum::() } #[cfg(test)]