Advent of Code 2024 Day 2

Author

Nathan Moore

— Day 2: Red-Nosed Reports —

At the nuclear plant there are some reports with different levels.

Analyze the unusual data from the engineers. How many reports are safe?

with open('data-2024-02.txt', 'r') as f:
    inp = f.read().splitlines()

report = [x.split() for x in inp]
report = [[int(y) for y in x] for x in report]
# report[0]
# report[1]

This seems like a function to check for increasing or decreasing amounts. Always changing but my no more than 3.

def checker(line):
    if line[0] == line[1]: 
        # same value, it's already out
        return 0
    elif line[0] < line[1]: 
        # print('up')
        # increasing values
        for i in range(len(line)):
            # print(i)
            if i+1 == len(line): 
                # end of the line, probable success
                return 1
            elif line[i] >= line[i+1]: 
                # same or decreasing
                return 0
            elif line[i+1] - line[i] > 3: 
                # too large gap
                return 0
            # else: 
            #     print('some other thing')
            #     print(line)
            #     return(9)
            
    elif line[0] > line[1]: 
        # print('down')
        # decreasing values
        for i in range(len(line)): 
            # print(i)
            if i+1 == len(line): 
                # end of line, probable success
                return 1
            elif line[i] <= line[i+1]: 
                # same or increasing 
                return 0
            elif line[i] - line[i+1] > 3:
                # gap too large
                return 0
            # else: 
            #     # uh oh
            #     print('some other thing')
            #     print(line)
            #     return 9
        
# report[994]
# checker(report[994])
outer = [checker(x) for x in report]

sum(outer)

# 624
624

— Part Two —

Maybe we can remove a level from each report and then see if they are safe.

Update your analysis by handling situations where the Problem Dampener can remove a single level from unsafe reports. How many reports are now safe?

Approach: use the function above, but wrap it in another function that remove pieces one at a time. Not totally efficient but easy enough to implement. Probably.

def wrapper(line): 
    # try to go first, if safe, all good
    safe = checker(line)
    if safe == 1: 
        return 1
    else: 
        # loop through and check if we get a safe report
        for i in range(len(line)): 
            newline = line[:i] + line[i+1:]
            if checker(newline) == 1: 
                return 1
        # if we haven't returned by now, return 0
        return 0
    
safer = [wrapper(x) for x in report]

sum(safer)

# 658
# not that much safer
658