day7: optimize away needing a second grid
This commit is contained in:
36
src/day7.rs
36
src/day7.rs
@@ -25,34 +25,36 @@ fn part1(input: &Grid<u8>) -> u64 {
|
||||
|
||||
#[aoc(day7, part2)]
|
||||
fn part2(input: &Grid<u8>) -> 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];
|
||||
}
|
||||
// if our current position is a . add that count here
|
||||
Some(b'.') => {
|
||||
grid.increment(&(x, y), n);
|
||||
col_counts[x] = 0;
|
||||
}
|
||||
_ => 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::<u64>()
|
||||
col_counts.iter().sum::<u64>()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
Reference in New Issue
Block a user