day(06): factor out the merging
Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
parent
a83cea78b7
commit
cb0f7fa445
1 changed files with 33 additions and 25 deletions
|
@ -12,6 +12,38 @@ struct Race {
|
|||
struct Day06 {
|
||||
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 {
|
||||
fn new<P: AsRef<Path>>(pathname: P) -> Self {
|
||||
let lines: Vec<String> = file_to_lines(pathname);
|
||||
|
@ -40,31 +72,7 @@ impl Solution<Output1, Output2> for Day06 {
|
|||
}
|
||||
|
||||
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
|
||||
},
|
||||
);
|
||||
let merged = self.merge_races();
|
||||
|
||||
(1..merged.time)
|
||||
.filter(|t| (merged.time - t) * t > merged.distance)
|
||||
|
|
Loading…
Reference in a new issue