Skip to content

Commit

Permalink
Year 2023, Day 15, part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
Peter Helbing committed Dec 16, 2023
1 parent 9930a84 commit e104f08
Showing 1 changed file with 50 additions and 2 deletions.
52 changes: 50 additions & 2 deletions year2023/src/day15.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,51 @@ impl Day for Day15 {
input.split(',').map(hash).sum::<usize>().to_string()
}

fn star2(&self, _input: &str) -> String {
String::from("not implemented")
fn star2(&self, input: &str) -> String {
let mut boxes: [_; 256] = std::array::from_fn(|_| vec![]);

let input = input.replace('\n', "");
for s in input.split(',') {
boxes = insert(boxes, s);
}

focusing_power(&boxes).to_string()
}
}

type Boxes<'a> = [Vec<(&'a str, usize)>; 256];

fn insert<'a>(mut boxes: Boxes<'a>, s: &'a str) -> Boxes<'a> {
if s.ends_with('-') {
let label = &s[0..s.len() - 1];
let target_box = &mut boxes[hash(label)];
if let Some(p) = target_box.iter().position(|(l, _)| l == &label) {
target_box.remove(p);
}
} else {
let (label, focal_length) = s.split_once('=').unwrap();
let focal_length = focal_length.parse().unwrap();
let target_box = &mut boxes[hash(label)];
if let Some(p) = target_box.iter().position(|(l, _)| l == &label) {
target_box[p].1 = focal_length;
} else {
target_box.push((label, focal_length));
}
}
boxes
}

fn focusing_power(boxes: &Boxes<'_>) -> usize {
boxes
.iter()
.enumerate()
.map(|(i, b)| {
b.iter()
.enumerate()
.map(|(j, (_, focal_length))| (i + 1) * (j + 1) * focal_length)
.sum::<usize>()
})
.sum::<usize>()
}

fn hash(s: &str) -> usize {
Expand All @@ -35,6 +77,12 @@ mod tests {
assert_eq!(d.star1(INPUT), "1320");
}

#[test]
fn ex2() {
let d = Day15 {};
assert_eq!(d.star2(INPUT), "145");
}

#[test]
fn test_hash() {
assert_eq!(hash("HASH"), 52);
Expand Down

0 comments on commit e104f08

Please sign in to comment.