13
submitted 11 months ago* (last edited 11 months ago) by Ategon@programming.dev to c/advent_of_code@programming.dev

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
[-] purplemonkeymad@programming.dev 3 points 11 months ago* (last edited 11 months ago)

This felt ... too simple. I think the hardest part of part two for me was reading comprehension. My errors were typically me not reading exactly was there.

Pythonimport re import math import argparse import itertools

def int_hash(string:str) -> int:
    hash = 0
    for c in [*string]:
        hash += ord(c)
        hash *= 17
        hash = hash % 256
    return hash

class Instruction:
    def __init__(self,string:str) -> None:
        label,action,strength = re.split('([-=])',string)
        self.label = label
        self.action = action
        if not strength:
            strength = 0
        self.strength = int(strength)
    
    def __repr__(self) -> str:
        return f"Instruction(l={self.label}, a={self.action}, s={self.strength})"
    
    def __str__(self) -> str:
        stren = str(self.strength if self.strength > 0 else '')
        return f"{self.label}{self.action}{stren}"


class Lens:
    def __init__(self,label:str,focal_length:int) -> None:
        self.label:str = label
        self.focal_length:int = focal_length

    def __repr__(self) -> str:
        return f"Lens(label:{self.label},focal_length:{self.focal_length})"
    
    def __str__(self) -> str:
        return f"[{self.label} {self.focal_length}]"

def main(line_list:str,part:int):
    init_sequence = line_list.splitlines(keepends=False)[0].split(',')
    sum = 0
    focal_array = dict[int,list[Lens]]()
    for i in range(0,256):
        focal_array[i] = list[Lens]()
    for s in init_sequence:
        hash_value = int_hash(s)
        sum += hash_value

        # part 2 stuff
        action = Instruction(s)
        position = int_hash(action.label)
        current_list = focal_array[position]
        existing_lens = list(filter(lambda x:x.label == action.label,current_list))
        if len(existing_lens) > 1:
            raise Exception("multiple of same lens in box, what do?")
        match action.action:
            case '-':
                if len(existing_lens) == 1:
                    current_list.remove(existing_lens[0])
            case '=':
                if len(existing_lens) == 0:
                    current_list.append(Lens(action.label,action.strength))
                if len(existing_lens) == 1:
                    existing_lens[0].focal_length = action.strength
            case _:
                raise Exception("unknown action")

    print(f"Part1: {sum}")
    #print(focal_array)

    sum2 = 0
    for i,focal_box in focal_array.items():
        for l,lens in enumerate(focal_box):
            sum2 += ( (i+1) * (l+1) * lens.focal_length )

    print(f"Part2: {sum2}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="template for aoc solver")
    parser.add_argument("-input",type=str)
    parser.add_argument("-part",type=int)
    args = parser.parse_args()
    filename = args.input
    if filename == None:
        parser.print_help()
        exit(1)
    part = args.part
    file = open(filename,'r')
    main(file.read(),part)
    file.close()

this post was submitted on 15 Dec 2023
13 points (100.0% liked)

Advent Of Code

764 readers
1 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