day 14 part 1

This commit is contained in:
Dominic 2023-12-14 13:15:14 +01:00
parent cbbee06a64
commit ffb9985fd3
Signed by: msrd0
GPG key ID: DCC8C247452E98F9
4 changed files with 188 additions and 0 deletions

80
src/bin/day14.rs Normal file
View file

@ -0,0 +1,80 @@
#![forbid(elided_lifetimes_in_paths, unsafe_code)]
use aatree::AATreeSet;
use aoc23::read;
use chumsky::prelude::*;
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Cell {
Void,
RollingStone,
PermanentStone
}
impl Cell {
fn parser() -> impl Parser<char, Self, Error = Simple<char>> {
choice((
just('.').map(|_| Self::Void),
just('O').map(|_| Self::RollingStone),
just('#').map(|_| Self::PermanentStone)
))
}
}
fn parser() -> impl Parser<char, Vec<Vec<Cell>>, Error = Simple<char>> {
Cell::parser()
.repeated()
.then_ignore(just("\n"))
.repeated()
.then_ignore(end())
}
fn main() -> anyhow::Result<()> {
let grid = read("inputs/day14.txt", parser())?;
let mut rolling_stones: AATreeSet<(usize, usize)> = grid
.iter()
.enumerate()
.flat_map(|(i, row)| {
row.iter()
.enumerate()
.filter(|(_, stone)| **stone == Cell::RollingStone)
.map(move |(j, _)| (i, j))
})
.collect();
// we skip the first row, no stones can be rolled north
let mut last_row = 0;
let mut last_col = grid[0].len();
while let Some((row, col)) = rolling_stones
.first_at_or_after(&(last_row, last_col + 1))
.copied()
{
let mut new_row = row;
while new_row > 0
&& !rolling_stones.contains(&(new_row - 1, col))
&& grid[new_row - 1][col] != Cell::PermanentStone
{
new_row -= 1;
}
if new_row != row {
rolling_stones.remove(&(row, col));
rolling_stones.insert((new_row, col));
}
last_row = row;
last_col = col;
}
let mut weight = 0;
for col in 0 .. grid[0].len() {
for row in 0 .. grid.len() {
if rolling_stones.contains(&(row, col)) {
weight += grid.len() - row;
}
}
}
println!("{weight}");
Ok(())
}