Skip to content

Latest commit

 

History

History
77 lines (63 loc) · 2.42 KB

15.md

File metadata and controls

77 lines (63 loc) · 2.42 KB

Day 15

Another refreshingly easy one!

Part 1 Part 2 Total
Time 3:06 12:35 15:41

Part 1

This part was ridiculously easy, no thinking, just do it. I had one hiccup because I accidentally hashed the entire input instead of just the comma-separated values individually.

from helpers.datagetter import aocd_data_in

din, aocd_submit = aocd_data_in(split=False, numbers=False)
ans = 0

for code in din.split(","):
    current_value = 0
    for c in code:
        current_value += ord(c)
        current_value *= 17
        current_value %= 256
    ans += current_value

aocd_submit(ans)

Part 2

I liked that Part 2 was significantly easier than Part 1, but boy, that was a lot of reading! Once read though, it was fairly straightforward. I used defaultdict to create the boxes that would contain the lenses, then just some simple logic for popping, replacing, or appending to the list. All the data structures were there, it was just about implementing it. Now I can go to bed early!

One area of improvement which would cut down the code would be making the hash algorithm into a function, but the way I did it does avoid one layer of nesting, so that's nice I suppose.

from helpers.datagetter import aocd_data_in
from collections import defaultdict

din, aocd_submit = aocd_data_in(split=False, numbers=False)
ans = 0

boxes = defaultdict(list)

for code in din.split(","):
    focal = 0
    if "-" in code:
        hsh = code.split("-")[0]
        operation = "-"
    else:
        hsh = code.split("=")[0]
        operation = "="
        focal = int(code.split("=")[1])

    current_value = 0
    for c in hsh:
        current_value += ord(c)
        current_value *= 17
        current_value %= 256

    if operation == "-":
        for i in range(len(boxes[current_value])):
            if boxes[current_value][i][0] == hsh:
                boxes[current_value].pop(i)
                break
    else:
        for i in range(len(boxes[current_value])):
            if boxes[current_value][i][0] == hsh:
                boxes[current_value].pop(i)
                boxes[current_value].insert(i, [hsh, focal])
                break
        else:
            boxes[current_value].append([hsh, focal])

for box_num, lenses in boxes.items():
    if not lenses:
        continue
    for i in range(len(lenses)):
        ans += (box_num + 1) * (i + 1) * (lenses[i][1])

aocd_submit(ans)