this post was submitted on 15 Dec 2023
14 points (93.8% liked)

Advent Of Code

770 readers
67 users here now

An unofficial home for the advent of code community on programming.dev!

Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

AoC 2023

Solution Threads

M T W T F S S
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25

Rules/Guidelines

Relevant Communities

Relevant Links

Credits

Icon base by Lorc under CC BY 3.0 with modifications to add a gradient

console.log('Hello World')

founded 1 year ago
MODERATORS
 

Day 15: Lens Library

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • Code block support is not fully rolled out yet but likely will be in the middle of the event. Try to share solutions as both code blocks and using something such as https://topaz.github.io/paste/ , pastebin, or github (code blocks to future proof it for when 0.19 comes out and since code blocks currently function in some apps and some instances as well if they are running a 0.19 beta)

FAQ


๐Ÿ”’ Thread is locked until there's at least 100 2 star entries on the global leaderboard

Edit: ๐Ÿ”“ Unlocked

you are viewing a single comment's thread
view the rest of the comments
[โ€“] capitalpb@programming.dev 3 points 11 months ago

Had to take a couple days off, but this was a nice one to come back to. Will have to find some time today to go back and do one or two of the 3 that I missed. I don't have much to say about this one - I had an idea almost immediately and it worked out without much struggle. There's probably some cleaner ways to write parts of this, but I'm not too disappointed with how it turned out.

https://github.com/capitalpb/advent_of_code_2023/blob/main/src/solvers/day15.rs

use crate::Solver;
use std::collections::HashMap;

#[derive(Debug)]
struct Lens {
    label: String,
    focal_length: u32,
}

fn hash_algorithm(input: &str) -> u32 {
    input
        .chars()
        .fold(0, |acc, ch| (acc + ch as u32) * 17 % 256)
}

pub struct Day15;

impl Solver for Day15 {
    fn star_one(&self, input: &str) -> String {
        input
            .trim_end()
            .split(',')
            .map(hash_algorithm)
            .sum::()
            .to_string()
    }

    fn star_two(&self, input: &str) -> String {
        let mut boxes: HashMap> = HashMap::new();

        for instruction in input.trim_end().split(',') {
            let (label, focal_length) = instruction
                .split_once(|ch| char::is_ascii_punctuation(&ch))
                .unwrap();

            let box_number = hash_algorithm(label);
            let lenses = boxes.entry(box_number).or_insert(vec![]);

            if focal_length == "" {
                lenses.retain(|lens| lens.label != label);
                continue;
            }

            let new_lens = Lens {
                label: label.to_string(),
                focal_length: focal_length.parse().unwrap(),
            };

            if let Some(lens_index) = lenses.iter().position(|lens| lens.label == new_lens.label) {
                lenses[lens_index].focal_length = new_lens.focal_length;
            } else {
                lenses.push(new_lens);
            }
        }

        boxes
            .iter()
            .map(|(box_number, lenses)| {
                lenses
                    .iter()
                    .enumerate()
                    .map(|(lens_index, lens)| {
                        (box_number + 1) * (lens_index as u32 + 1) * lens.focal_length
                    })
                    .sum::()
            })
            .sum::()
            .to_string()
    }
}