1
0
Fork 0

day(06): factor out the merging

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2023-12-06 17:09:02 +01:00
parent a83cea78b7
commit cb0f7fa445
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -12,6 +12,38 @@ struct Race {
struct Day06 { struct Day06 {
races: Vec<Race>, races: Vec<Race>,
} }
impl Day06 {
fn count_digits(mut n: i64, radix: i64) -> u32 {
let mut digits = 0;
while n > 0 {
n /= radix;
digits += 1;
}
digits
}
fn merge_races(&self) -> Race {
self.races.iter().fold(
Race {
time: 0,
distance: 0,
},
|mut m, r| {
m.time *= 10_i64.pow(Self::count_digits(r.time, 10));
m.distance *= 10_i64.pow(Self::count_digits(r.distance, 10));
m.time += r.time;
m.distance += r.distance;
m
},
)
}
}
impl Solution<Output1, Output2> for Day06 { impl Solution<Output1, Output2> for Day06 {
fn new<P: AsRef<Path>>(pathname: P) -> Self { fn new<P: AsRef<Path>>(pathname: P) -> Self {
let lines: Vec<String> = file_to_lines(pathname); let lines: Vec<String> = file_to_lines(pathname);
@ -40,31 +72,7 @@ impl Solution<Output1, Output2> for Day06 {
} }
fn part_2(&mut self) -> Output2 { fn part_2(&mut self) -> Output2 {
let merged = self.races.iter().fold( let merged = self.merge_races();
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) (1..merged.time)
.filter(|t| (merged.time - t) * t > merged.distance) .filter(|t| (merged.time - t) * t > merged.distance)