day15: functional hash implementation using fold()

This commit is contained in:
Keenan Tims 2023-12-14 23:33:48 -08:00
parent eac460417c
commit e12c0134b0
Signed by: ktims
GPG Key ID: 11230674D69038D4

View File

@ -27,13 +27,12 @@ fn main() {
// COMMON // COMMON
fn hash_string(s: &str) -> u64 { fn hash_string(s: &str) -> u64 {
let mut val = 0u64; s.bytes().fold(0u64, |mut accum, val| {
for c in s.bytes() { accum += val as u64;
val += c as u64; accum *= 17;
val *= 17; accum %= 256;
val %= 256; accum
} })
val
} }
// PROBLEM 1 solution // PROBLEM 1 solution
@ -80,8 +79,12 @@ impl LensBox {
} }
} }
fn total_lens_power(&self) -> u64{ fn total_lens_power(&self) -> u64 {
self.order.iter().enumerate().map(|(lens_idx, label)| (lens_idx+1) as u64 * self.lenses[label] as u64).sum() self.order
.iter()
.enumerate()
.map(|(lens_idx, label)| (lens_idx + 1) as u64 * self.lenses[label] as u64)
.sum()
} }
} }
@ -137,7 +140,11 @@ fn problem2<T: BufRead>(mut input: Lines<T>) -> u64 {
inst.execute(&mut boxes); inst.execute(&mut boxes);
} }
boxes.iter().enumerate().map(|(box_idx, b)| (box_idx + 1) as u64 * b.total_lens_power()).sum() boxes
.iter()
.enumerate()
.map(|(box_idx, b)| (box_idx + 1) as u64 * b.total_lens_power())
.sum()
} }
#[cfg(test)] #[cfg(test)]