diff --git a/2023/benches/days.rs b/2023/benches/days.rs index 22d3836..5340d9d 100644 --- a/2023/benches/days.rs +++ b/2023/benches/days.rs @@ -9,7 +9,7 @@ use criterion::Criterion; use aoc_2023::get_implementation; /// Number of days we have an implementation to benchmark -const DAYS_IMPLEMENTED: u8 = 4; +const DAYS_IMPLEMENTED: u8 = 5; fn read_input(day: u8) -> std::io::Result> { let input_path = format!("inputs/{day:02}.txt"); diff --git a/2023/src/day05.rs b/2023/src/day05.rs index 6ca3342..1e43ecc 100644 --- a/2023/src/day05.rs +++ b/2023/src/day05.rs @@ -1,6 +1,5 @@ use anyhow::Context; use nom::bytes::complete::tag; -use nom::bytes::complete::take_until; use nom::character::complete::newline; use nom::combinator::map; use nom::multi::many1; @@ -102,27 +101,38 @@ fn follow_mapping(node: u64, mappings: &[Mapping]) -> u64 { } } +fn follow_all_mappings(mut node: u64, mappings: &[Vec]) -> u64 { + for mappings in mappings { + node = follow_mapping(node, mappings) + } + node +} + pub fn part1(input: &[u8]) -> anyhow::Result { let almanac = parse_input(input, parse_almanac)?; let min = almanac .seeds .iter() - .map(|node| { - let mut node = *node; - for mappings in &almanac.mappings { - node = follow_mapping(node, mappings) - } - node - }) + .map(|node| follow_all_mappings(*node, &almanac.mappings)) .min() .context("Unreachable, no seeds but parser ensures seeds")?; Ok(min.to_string()) } -pub fn part2(_input: &[u8]) -> anyhow::Result { - anyhow::bail!("Not implemented") +pub fn part2(input: &[u8]) -> anyhow::Result { + let almanac = parse_input(input, parse_almanac)?; + + let min = almanac + .seeds + .chunks_exact(2) + .flat_map(|c| c[0]..c[0] + c[1]) + .map(|node| follow_all_mappings(node, &almanac.mappings)) + .min() + .context("Unreachable, no seeds but parser ensures seeds")?; + + Ok(min.to_string()) } #[cfg(test)] @@ -135,4 +145,9 @@ mod tests { fn sample_part1() { assert_eq!(part1(SAMPLE).unwrap(), "35"); } + + #[test] + fn sample_part2() { + assert_eq!(part2(SAMPLE).unwrap(), "46"); + } } diff --git a/2023/src/samples/05.txt b/2023/src/samples/05.txt new file mode 100644 index 0000000..f756727 --- /dev/null +++ b/2023/src/samples/05.txt @@ -0,0 +1,33 @@ +seeds: 79 14 55 13 + +seed-to-soil map: +50 98 2 +52 50 48 + +soil-to-fertilizer map: +0 15 37 +37 52 2 +39 0 15 + +fertilizer-to-water map: +49 53 8 +0 11 42 +42 0 7 +57 7 4 + +water-to-light map: +88 18 7 +18 25 70 + +light-to-temperature map: +45 77 23 +81 45 19 +68 64 13 + +temperature-to-humidity map: +0 69 1 +1 0 69 + +humidity-to-location map: +60 56 37 +56 93 4