From a83cea78b7566f90c2167f9ddbf98b8219e9ea0d Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 6 Dec 2023 15:30:22 +0100 Subject: [PATCH] day(06): add solution Signed-off-by: Matej Focko --- samples/day06.txt | 2 ++ src/bin/day06.rs | 80 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 samples/day06.txt create mode 100644 src/bin/day06.rs diff --git a/samples/day06.txt b/samples/day06.txt new file mode 100644 index 0000000..28f5ae9 --- /dev/null +++ b/samples/day06.txt @@ -0,0 +1,2 @@ +Time: 7 15 30 +Distance: 9 40 200 diff --git a/src/bin/day06.rs b/src/bin/day06.rs new file mode 100644 index 0000000..266adfd --- /dev/null +++ b/src/bin/day06.rs @@ -0,0 +1,80 @@ +use aoc_2023::*; + +type Output1 = i32; +type Output2 = Output1; + +#[derive(Debug)] +struct Race { + time: i64, + distance: i64, +} + +struct Day06 { + races: Vec, +} +impl Solution for Day06 { + fn new>(pathname: P) -> Self { + let lines: Vec = file_to_lines(pathname); + + let times: Vec = parse_ws_separated(lines[0].split(':').nth(1).unwrap()); + let distances: Vec = parse_ws_separated(lines[1].split(':').nth(1).unwrap()); + + let races = times + .iter() + .zip(distances.iter()) + .map(|(&time, &distance)| Race { time, distance }) + .collect(); + + Self { races } + } + + fn part_1(&mut self) -> Output1 { + self.races + .iter() + .map(|r| { + (1..r.time) + .filter(|t| (r.time - t) * t > r.distance) + .count() as i32 + }) + .product() + } + + fn part_2(&mut self) -> Output2 { + let merged = self.races.iter().fold( + Race { + time: 0, + distance: 0, + }, + |mut m, r| { + let mut t = r.time; + let mut d = r.distance; + + while t > 0 { + m.time *= 10; + t /= 10; + } + + while d > 0 { + m.distance *= 10; + d /= 10; + } + + m.time += r.time; + m.distance += r.distance; + + m + }, + ); + + (1..merged.time) + .filter(|t| (merged.time - t) * t > merged.distance) + .count() as i32 + } +} + +fn main() -> Result<()> { + // Day06::run("sample") + Day06::main() +} + +test_sample!(day_06, Day06, 288, 71503);