day 11 part 1
This commit is contained in:
parent
998dfd5c61
commit
c6fc7ded50
2 changed files with 223 additions and 0 deletions
83
src/bin/day11.rs
Normal file
83
src/bin/day11.rs
Normal file
|
@ -0,0 +1,83 @@
|
|||
#![forbid(elided_lifetimes_in_paths, unsafe_code)]
|
||||
|
||||
use aoc23::read;
|
||||
use chumsky::prelude::*;
|
||||
use std::collections::HashSet;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
enum Cell {
|
||||
Void,
|
||||
Galaxy
|
||||
}
|
||||
|
||||
impl Cell {
|
||||
fn parser() -> impl Parser<char, Self, Error = Simple<char>> {
|
||||
choice((
|
||||
just('.').map(|_| Self::Void),
|
||||
just('#').map(|_| Self::Galaxy)
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
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 universe = read("inputs/day11.txt", parser())?;
|
||||
|
||||
let empty_rows: HashSet<usize> = universe
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, row)| row.iter().all(|cell| *cell == Cell::Void))
|
||||
.map(|(i, _)| i)
|
||||
.collect();
|
||||
let empty_cols: HashSet<usize> = universe
|
||||
.first()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, _)| i)
|
||||
.filter(|i| universe.iter().all(|row| row[*i] == Cell::Void))
|
||||
.collect();
|
||||
|
||||
let galaxies: Vec<(usize, usize)> = universe
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(i, row)| row.iter().enumerate().map(move |(j, cell)| (i, j, *cell)))
|
||||
.filter(|(_, _, cell)| *cell == Cell::Galaxy)
|
||||
.map(|(i, j, _)| (i, j))
|
||||
.collect();
|
||||
|
||||
let mut sum = 0_u64;
|
||||
for (i, g) in galaxies.iter().enumerate() {
|
||||
for (_j, h) in galaxies.iter().enumerate().skip(i + 1) {
|
||||
let mut x = [g.0, h.0];
|
||||
x.sort_unstable();
|
||||
let mut dist = (x[0] .. x[1])
|
||||
.map(|row| match empty_rows.contains(&row) {
|
||||
true => 2,
|
||||
false => 1
|
||||
})
|
||||
.sum::<u64>();
|
||||
|
||||
let mut y = [g.1, h.1];
|
||||
y.sort_unstable();
|
||||
dist += (y[0] .. y[1])
|
||||
.map(|col| match empty_cols.contains(&col) {
|
||||
true => 2,
|
||||
false => 1
|
||||
})
|
||||
.sum::<u64>();
|
||||
// eprintln!(" - Between galaxy {} and galaxy {}: {dist}", i + 1, _j + 1);
|
||||
sum += dist;
|
||||
}
|
||||
}
|
||||
println!("{sum}");
|
||||
|
||||
Ok(())
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue