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

Day 9: Mirage Maintenance

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

๐Ÿ”“ Unlocked after 5 mins

you are viewing a single comment's thread
view the rest of the comments
[-] purplemonkeymad@programming.dev 2 points 11 months ago

Using a class here actually made part 2 super simple, just copy and paste a function. Initially I was a bit concerned about what part 2 would be, but looking at the lengths of the input data, there looked to be a resonable limit to how many additional rows there could be.

pythonimport re import math import argparse import itertools

#https://stackoverflow.com/a/1012089
def iter_item_and_next(iterable):
    items, nexts = itertools.tee(iterable, 2)
    nexts = itertools.chain(itertools.islice(nexts, 1, None), [None])
    return zip(items, nexts)

class Sequence:
    def __init__(self,sequence:list) -> None:
        self.list = sequence
        if all([x == sequence[0] for x in sequence]):
            self.child:Sequence = ZeroSequence(len(sequence)-1)
            return
        
        child_sequence = list()
        for cur,next in iter_item_and_next(sequence):
            if next == None:
                continue
            child_sequence.append(next - cur)

        if len(child_sequence) > 1:
            self.child:Sequence = Sequence(child_sequence)
            return
        
        # can't do diff on single item, use zero list
        self.child:Sequence = ZeroSequence(1)

    def __repr__(self) -> str:
        return f"Sequence([{self.list}], Child:{self.child})"

    def getNext(self) -> int:
        if self.child == None:
            new = self.list[-1]
        else: 
            new = self.list[-1] + self.child.getNext()

        self.list.append(new)
        return new
    
    def getPrevious(self) -> int:
        if self.child == None:
            new = self.list[0]
        else: 
            new = self.list[0] - self.child.getPrevious()

        self.list.insert(0,new)
        return new

class ZeroSequence(Sequence):
    def __init__(self,count) -> None:
        self.list = [0]*count
        self.child = None

    def __repr__(self) -> str:
        return f"ZeroSequence(length={len(self.list)})"

    def getNext(self) -> int:
        self.list.append(0)
        return 0
    
    def getPrevious(self) -> int:
        self.list.append(0)
        return 0

def parse_line(string:str) -> list:
    return [int(x) for x in string.split(' ')]

def main(line_list):
    data = [Sequence(parse_line(x)) for x in line_list]
    print(data)

    # part 1
    total = 0
    for d in data:
        total += d.getNext()
    print("Part 1 After:")
    print(data)
    print(f"part 1 total: {total}")

    # part 2
    total = 0
    for d in data:
        total += d.getPrevious()
    print("Part 2 After:")
    print(data)
    print(f"part 2 total: {total}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="day 1 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)
    file = open(filename,'r')
    main([line.rstrip('\n') for line in file.readlines()])
    file.close()

this post was submitted on 09 Dec 2023
21 points (95.7% liked)

Advent Of Code

736 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