Skip to content

Commit

Permalink
day3 was too much reading
Browse files Browse the repository at this point in the history
  • Loading branch information
kellegous committed Dec 9, 2021
1 parent b9827f1 commit b5e6309
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions src/day3/main.rs
Expand Up @@ -8,6 +8,19 @@ struct Report {
vals: Vec<u16>,
}

fn segment(vals: &[u16], m: u16) -> (Vec<u16>, Vec<u16>) {
let mut a = Vec::new();
let mut b = Vec::new();
for val in vals {
if (val & m) != 0 {
a.push(*val);
} else {
b.push(*val);
}
}
(a, b)
}

impl Report {
fn from_reader<R: Read>(r: R) -> Result<Report, Box<dyn Error>> {
let r = BufReader::new(r);
Expand Down Expand Up @@ -37,6 +50,27 @@ impl Report {

g * (!g & ((1 << self.n) - 1))
}

fn part2(&self) -> usize {
let mask = 1 << (self.n - 1);
let (mut a, mut b) = segment(&self.vals, mask);

let mut m = mask >> 1;
while a.len() > 1 {
let (aa, bb) = segment(&a, m);
a = if aa.len() >= bb.len() { aa } else { bb };
m >>= 1;
}

let mut m = mask >> 1;
while b.len() > 1 {
let (aa, bb) = segment(&b, m);
b = if aa.len() < bb.len() { aa } else { bb };
m >>= 1;
}

a[0] as usize * b[0] as usize
}
}

fn main() -> Result<(), Box<dyn Error>> {
Expand All @@ -53,6 +87,7 @@ fn main() -> Result<(), Box<dyn Error>> {
)?)?;

println!("Part #1: {}", report.part1());
println!("Part #2: {}", report.part2());

Ok(())
}

0 comments on commit b5e6309

Please sign in to comment.