Day 2 part 1

This commit is contained in:
traxys 2025-12-02 14:18:46 +01:00
parent 14306595bd
commit 9c74b744a8

108
src/bin/day2.rs Normal file
View file

@ -0,0 +1,108 @@
use std::time::Instant;
use aoc_2025::{load, print_res};
use bstr::BString;
use color_eyre::eyre::Context;
type Parsed<'a> = Vec<(u64, u64)>;
#[inline(never)]
pub fn parsing(input: &BString) -> color_eyre::Result<Parsed<'_>> {
str::from_utf8(input)?
.trim()
.split(',')
.map(|r| {
let Some((left, right)) = r.split_once('-') else {
color_eyre::eyre::bail!("Invalid range: {r}");
};
Ok((
left.parse()
.with_context(|| format!("While parsing left value `{left}`"))?,
right
.parse()
.with_context(|| format!("While parsing right value `{right}`"))?,
))
})
.collect()
}
#[inline(never)]
pub fn part1(input: Parsed) {
let mut invalid_id_sum = 0;
for (start, end) in input {
let mut s = start;
let mut e = end;
let mut mag_s = s.ilog10() + 1;
let mut mag_e = e.ilog10() + 1;
// All ranges are of an odd length
if mag_s % 2 == 1 && mag_s == mag_e {
continue;
}
// Reduce e such that it has an even number of digits
if mag_e % 2 == 1 {
mag_e -= 1;
e = 10u64.pow(mag_e) - 1;
}
if mag_s % 2 == 1 {
s = 10u64.pow(mag_s);
mag_s += 1;
}
// Right now we only handle ranges with the same span
if mag_s != mag_e {
panic!();
}
let half_mag = mag_s / 2;
let pow10 = 10u64.pow(half_mag);
let high_start = s / pow10;
let high_end = e / pow10;
for invalid_part in high_start..=high_end {
let invalid = invalid_part * pow10 + invalid_part;
if invalid < start {
continue
}
if invalid > end {
break
}
invalid_id_sum += invalid;
}
}
print_res!("Sum of invalid IDs: {invalid_id_sum}");
}
#[inline(never)]
pub fn part2(input: Parsed) {
todo!("todo part2")
}
pub fn main() -> color_eyre::Result<()> {
let context = load()?;
let start = Instant::now();
let parsed = parsing(&context.input)?;
let elapsed = humantime::format_duration(start.elapsed());
let start = Instant::now();
if context.part == 1 {
part1(parsed);
} else {
part2(parsed);
}
let elapsed_part = humantime::format_duration(start.elapsed());
println!(" Parsing: {elapsed}");
println!(" Solving: {elapsed_part}");
Ok(())
}