day7: optimize away needing a second grid

This commit is contained in:
2025-12-07 01:14:29 -08:00
parent 30644bcbfc
commit ba2cfffc3f

View File

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