summaryrefslogtreecommitdiff
path: root/2023/src/bin/day_15.rs
blob: badb34f7605bb1fc47511fd599510f5f9d2dedd4 (plain)
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
use std::fs;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let input = fs::read_to_string("inputs/day_15.txt")?;
    let parsed = InitializationInstructions::parse(&input);
    dbg!(&parsed.hash_sum());

    Ok(())
}

#[derive(Debug)]
struct InitializationInstructions(Vec<String>);

impl InitializationInstructions {
    fn parse(input: &str) -> Self {
        Self(input.trim().split(",").map(|s| s.to_owned()).collect())
    }

    fn hash_sum(&self) -> u32 {
        self.0.iter().map(|s| hash(&s)).sum()
    }
}

fn hash(input: &str) -> u32 {
    let mut result: u32 = 0;
    for c in input.bytes() {
        result += Into::<u32>::into(c);
        result *= 17;
        result %= 256;
    }
    result
}

#[test]
fn examples() {
    assert_eq!(hash("rn=1"), 30);
    assert_eq!(hash("cm-"), 253);
    assert_eq!(hash("qp=3"), 97);
    assert_eq!(hash("cm=2"), 47);
    assert_eq!(hash("qp-"), 14);
    assert_eq!(hash("pc=4"), 180);
    assert_eq!(hash("ot=9"), 9);
    assert_eq!(hash("ab=5"), 197);
    assert_eq!(hash("pc-"), 48);
    assert_eq!(hash("pc=6"), 214);
    assert_eq!(hash("ot=7"), 231);
}