Brute force day 2023 day 5 part 2

This commit is contained in:
2023-12-05 09:10:16 +01:00
parent b7797c40aa
commit 63c1024d22
3 changed files with 59 additions and 11 deletions

View File

@@ -9,7 +9,7 @@ use criterion::Criterion;
use aoc_2023::get_implementation; use aoc_2023::get_implementation;
/// Number of days we have an implementation to benchmark /// 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<Vec<u8>> { fn read_input(day: u8) -> std::io::Result<Vec<u8>> {
let input_path = format!("inputs/{day:02}.txt"); let input_path = format!("inputs/{day:02}.txt");

View File

@@ -1,6 +1,5 @@
use anyhow::Context; use anyhow::Context;
use nom::bytes::complete::tag; use nom::bytes::complete::tag;
use nom::bytes::complete::take_until;
use nom::character::complete::newline; use nom::character::complete::newline;
use nom::combinator::map; use nom::combinator::map;
use nom::multi::many1; 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<Mapping>]) -> u64 {
for mappings in mappings {
node = follow_mapping(node, mappings)
}
node
}
pub fn part1(input: &[u8]) -> anyhow::Result<String> { pub fn part1(input: &[u8]) -> anyhow::Result<String> {
let almanac = parse_input(input, parse_almanac)?; let almanac = parse_input(input, parse_almanac)?;
let min = almanac let min = almanac
.seeds .seeds
.iter() .iter()
.map(|node| { .map(|node| follow_all_mappings(*node, &almanac.mappings))
let mut node = *node;
for mappings in &almanac.mappings {
node = follow_mapping(node, mappings)
}
node
})
.min() .min()
.context("Unreachable, no seeds but parser ensures seeds")?; .context("Unreachable, no seeds but parser ensures seeds")?;
Ok(min.to_string()) Ok(min.to_string())
} }
pub fn part2(_input: &[u8]) -> anyhow::Result<String> { pub fn part2(input: &[u8]) -> anyhow::Result<String> {
anyhow::bail!("Not implemented") 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)] #[cfg(test)]
@@ -135,4 +145,9 @@ mod tests {
fn sample_part1() { fn sample_part1() {
assert_eq!(part1(SAMPLE).unwrap(), "35"); assert_eq!(part1(SAMPLE).unwrap(), "35");
} }
#[test]
fn sample_part2() {
assert_eq!(part2(SAMPLE).unwrap(), "46");
}
} }

33
2023/src/samples/05.txt Normal file
View File

@@ -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