1
0
Fork 0

day(06): add solution

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2023-12-06 15:30:22 +01:00
parent 370b00c0c9
commit a83cea78b7
Signed by: mfocko
GPG key ID: 7C47D46246790496
2 changed files with 82 additions and 0 deletions

2
samples/day06.txt Normal file
View file

@ -0,0 +1,2 @@
Time: 7 15 30
Distance: 9 40 200

80
src/bin/day06.rs Normal file
View file

@ -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<Race>,
}
impl Solution<Output1, Output2> for Day06 {
fn new<P: AsRef<Path>>(pathname: P) -> Self {
let lines: Vec<String> = file_to_lines(pathname);
let times: Vec<i64> = parse_ws_separated(lines[0].split(':').nth(1).unwrap());
let distances: Vec<i64> = 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);