Solve day 7 in Rust

This commit is contained in:
George Thomas 2026-01-12 18:23:58 +00:00
parent 1a06ea1b51
commit 2462a30b1d
3 changed files with 95 additions and 1 deletions

View File

@ -7,16 +7,18 @@ use puzzles::day3;
use puzzles::day4; use puzzles::day4;
use puzzles::day5; use puzzles::day5;
use puzzles::day6; use puzzles::day6;
use puzzles::day7;
use std::fs; use std::fs;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
const PUZZLES: [&dyn SomePuzzle; 6] = [ const PUZZLES: [&dyn SomePuzzle; 7] = [
&day1::PUZZLE, &day1::PUZZLE,
&day2::PUZZLE, &day2::PUZZLE,
&day3::PUZZLE, &day3::PUZZLE,
&day4::PUZZLE, &day4::PUZZLE,
&day5::PUZZLE, &day5::PUZZLE,
&day6::PUZZLE, &day6::PUZZLE,
&day7::PUZZLE,
]; ];
fn main() { fn main() {

91
rust/puzzles/day7.rs Normal file
View File

@ -0,0 +1,91 @@
use crate::puzzle::Puzzle;
use itertools::Itertools;
use nom::{
Parser,
branch::alt,
character::complete::{char, newline},
combinator::{eof, value},
error::Error,
multi::{many1, separated_list1},
sequence::terminated,
};
use std::collections::{HashMap, HashSet};
pub const PUZZLE: Puzzle<(usize, Vec<HashSet<usize>>), 2> = Puzzle {
number: 7,
parser: |input| {
terminated::<_, _, Error<&str>, _, _>(
terminated(
(
terminated(
many1(alt((value(false, char('.')), value(true, char('S'))))),
newline,
)
.map_opt(|v| v.into_iter().position(|b| b)),
separated_list1(
newline,
many1(alt((value(false, char('.')), value(true, char('^'))))),
)
.map(|rows| {
rows.into_iter()
.map(|row| {
row.into_iter()
.enumerate()
.filter(|(_, b)| *b)
.map(|(i, _)| i)
.collect()
})
.collect()
}),
),
newline,
),
eof,
)
.parse(input)
.unwrap()
.1
},
parts: [
|(start, splitter_rows)| {
let mut beams = HashSet::from([*start]);
let mut count = 0;
for splitters in splitter_rows {
beams = beams
.iter()
.flat_map(|x| {
if splitters.contains(x) {
count += 1;
vec![x - 1, x + 1]
} else {
vec![*x]
}
})
.collect();
}
count.to_string()
},
|(start, splitter_rows)| {
let mut beams = HashMap::from([(*start, 1)]);
for splitters in splitter_rows {
beams = beams
.into_iter()
.flat_map(|(x, n)| {
if splitters.contains(&x) {
vec![x - 1, x + 1]
} else {
vec![x]
}
.into_iter()
.map(|x1| (x1, n))
.collect_vec()
})
.into_group_map()
.into_iter()
.map(|(k, vs)| (k, vs.into_iter().sum()))
.collect();
}
beams.values().sum::<usize>().to_string()
},
],
};

View File

@ -4,3 +4,4 @@ pub(crate) mod day3;
pub(crate) mod day4; pub(crate) mod day4;
pub(crate) mod day5; pub(crate) mod day5;
pub(crate) mod day6; pub(crate) mod day6;
pub(crate) mod day7;