aboutsummaryrefslogtreecommitdiff
path: root/src/day15pt2.rs
blob: 6f9e53c7dd803df4265924f203948596a1068648 (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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
fn hash(s: String) -> u64 {
    let mut sum: u64 = 0;
    for c in s.chars() {
        sum += c as u64;
        sum *= 17;
        sum %= 256;
    }
    return sum;
}

pub fn main() {
    let txt = std::fs::read_to_string("./input/day15.txt").unwrap();

    let input = txt.trim().split(",");
    let mut boxes: [Vec<&str>; 256] = vec![Vec::new(); 256].try_into().expect("static");

    for s in input {
        let fp;
        if s.chars().last().unwrap() == '-' {
            fp = s.split("-").collect::<Vec<_>>();
        } else {
            fp = s.split("=").collect::<Vec<_>>();
        }

        let box_ind = hash(fp[0].to_string()) as usize;

        if fp[1].len() != 0 {
            // dodaj
            let mut ind = true;
            for el in boxes[box_ind].iter_mut() {
                if el.split("=").collect::<Vec<_>>()[0] == fp[0] {
                    *el = s;
                    ind = false;
                    break;
                }
            }
            if ind {
                boxes[box_ind].push(s);
            }
        } else {
            // obrisi
            let mut x = -1;
            for i in 0..boxes[box_ind].len() {
                if boxes[box_ind][i].split("=").collect::<Vec<_>>()[0] == fp[0] {
                    x = i as isize;
                    break;
                }
            }
            if x != -1 {
                boxes[box_ind].remove(x as usize);
            }
        }
    }

    let mut sum: u64 = 0;

    for (i, b) in (&boxes).iter().enumerate() {
        for (j, l) in b.iter().enumerate() {
            sum += (i + 1) as u64
                * (j + 1) as u64
                * (l.split("=").collect::<Vec<_>>()[1])
                    .parse::<u64>()
                    .unwrap();
        }
    }

    println!("{}", sum);
}