Advent of Code

Advent of Code 2022, Day 11

So, now that you’re foraging through the jungle alone, you have discovered that Monkeys have stolen your items and are tossing them around. Use MATH to build a shotgun out of bamboo reeds and vines and stop the Monkeys!

No wait, that’s not friendly. Instead maybe calculate the rounds your items spend being tossed around based on some Mysterious Monkey Criteria and try to get your items back. There is probably some easy library to process the input, but that’s not how I’m rolling on these puzzles, so like 90% of this problem was processing the “Almost a dictionary input” into a format that json.loads would accept and transform into a dictionary. Then massaging that data just a bit more because my loop was adding an empty item each iteration and breaking things, but I can’t just lop that item off because the initial data doesn’t have an empty item. That’s easily fixed by adding an empty item to the initial data.

Part 1 does this loop for 20 rounds.

Part 2 does it for 10,000 rounds. (with slight modification to the code)

This is where some fancy library would probably be better, but instead I just, left my laptop running and made lunch…. and played some Fortnite… and probably made supper too, I’m not sure I am not there yet, it’s still lunch time while I am writing this. I am feeling confident it will work though. It hasn’t creashed yet at least. But maybe It will run out of memory before it can finish…. Or the heat death of the universe….

Or I can use the “Modulo Trick” which is to reduce the numbers down each round by a common multiple. Which literally finished in seconds, and was correct the first try.

Also, I can’t spell “Monkeys” but fuck it, I am leaving it.

import math
import json

with open("Day11Input.txt") as file:
    data = file.read()

split = data.split("\n\n")

monkies = {}

for each in split:
    each = each.replace('Monkey ', '{"')
    each = each.replace(': ', '": "')
    each = each.replace('\n  ', '", "')
    each = each.replace(':", "Starting ', '": {"')
    each = each.replace('new = old ', '')
    each = each.replace('divisible by ', '')
    each = each.replace('  If t', 'T')
    each = each.replace('  If f', 'F')
    each = each.replace('throw to monkey ', '')
    each = each + '"}}'
    monkies.update(json.loads(each))

monkey_list = monkies.keys()
num_monks = len(monkey_list)

# Part1
# rounds = 20
# Part2
rounds = 10000

common_multiple = 1
# print(monkies['3'])
for monk in range(0, num_monks):
    monkies[str(monk)]["item_count"] = 0
    monkies[str(monk)]["items"] = ", "+monkies[str(monk)]["items"]
    common_multiple *= int(monkies[str(monk)]["Test"])

for i in range(rounds):
    for monk in range(0, num_monks):
        # print(monk)
        items = monkies[str(monk)]["items"].split(", ")
        # print(items)
        if len(items) > 0:
            for item in items[1:]:
                monkies[str(monk)]["item_count"] += 1
                operations = monkies[str(monk)]["Operation"].split(" ")
                if operations[1] == "old":
                    # Part 1
                    # test_case = math.floor((int(item) * int(int(item)))/3)
                    # Part 2
                    test_case = math.floor((int(item) * int(int(item))))
                elif operations[0] == "*":
                    # Part 1
                    # test_case = math.floor((int(item) * int(operations[1]))/3)
                    # Part 2
                    test_case = math.floor((int(item) * int(operations[1])))
                else:
                    # Part 1
                    # test_case = math.floor((int(item) + int(operations[1]))/3)
                    # Part 2
                    test_case = math.floor((int(item) + int(operations[1])))
                if test_case % int(monkies[str(monk)]["Test"]) == 0:
                    throw_to = monkies[str(monk)]["True"]
                else:
                    throw_to = monkies[str(monk)]["False"]
                monkies[throw_to]["items"] = monkies[throw_to]["items"] + ", "+str(test_case%common_multiple)
        monkies[str(monk)]["items"] = ""

# print(monkies)

item_counts = []
for monk in range(0, num_monks):
    item_counts.append(monkies[str(monk)]["item_count"])

item_counts.sort(reverse=True)
print(item_counts[0]*item_counts[1])
# 25738411485

Advent of Code 2022, Day 10

Wheeeeee another Easy Mode/Hard Mode day. Ok, the hard mode is, debatable-ish. It was pretty tedious to get working, though the basic idea was pretty obvious.

Today’s puzzle, the communicator from a previous puzzle is broken, and the screen needs fixed. So you get an input of data off the broken communicator. For Part 1, you find some totals of the fluctuating signal level and add them up for a solution. Pretty simple honestly.

Then part two. Whoo boy, Part 2.

For Part 2, the data needs decoded into a series of letters. The biggest hassle, was figuring out exactly what the instructions were asking. There was a stepped through example, but it ended a bit too early to really get an idea of what was happening. This visualization someone posted to Reddit, helps a LOT. It made it much more clear how to process the data.

I still wasn’t getting a proper answer. I wasn’t even getting the proper result for the sample data set, but, oddly, I was ALMOST getting the sample data set result. Like, the first line was fine, halfway through the second line, it just went off and became spotty. I solved that, but more on that in a bit, because it was the end.

I also feel like I overly complicated things by using a 2×2 matrix of data, instead of just a long string then splitting the result to print it. But the 2×2 Matrix seemed more fun. It would almost be fun to connect this code up to an LED Matrix screen for the result.

Anyway, after lots and lots of tweaking to my original loop for Part 1, which is probably non existent now, I manage to get the solution. I had to change how I was handling the signals, because one type used 2 cycles, and the other took one. I had to add several variables to account for the position in the matrix. Though tracking that wasn’t too hard using the mod (remainder) operator and some basic division.

I’m a little disappointed in my result, because I used an import on “math” so I could round the division result down. One thing I usually try to do with these is just use, Pure Python. A lot of replies on Mastodon to previous posts suggest different modules, most often Numpy, but I really like the extra little challenge of “No Imports, pure Python”. The annoying part is, I could modify the code a bit to make the math work without using “floor” from “math”, but I’ve been working on this off and on all day, and it works, so I don’t really care to bother.

I also realized I needed to account for looping the pixel placer around. Something I would not have needed had I just used long string instead of a 2×2 matrix.

Anyway, After sons of modifications, and maybe I need a +1 here or a -1 here, I managed to solve it, which I said I would get to. I had enclosed the Pixel Placing algorithm inside the signal generating commands only. I had stupidly assumed, “noop” (No Operation) meant “Do nothing”. It just means, the signal doesn’t change. So I rearranged things a bit so the loop always ran, just sometimes once, sometimes twice, and poof, there it was, the answer! Mostly, there was a pixel off at the end, probably side effect of my looping, but I had the result and it worked.

import math

with open("Day10Input.txt") as file:
    data = file.read()

moves = data.split('\n')

def make_display(pixels,lines):
    display = []
    display_line = []
    for n in range(pixels):
        display_line.append(" ")
    for i in range(lines):
        display.append(display_line.copy())
    return display

def show_display(display):
    for each in display:
        print("".join(each))
    print("\n")

signal_strengths = [0, 1]
cycles = 0
signal = 1 # X In the instructions
line = 0

display = make_display(40, 6)

for move in moves:
    command = move.split(" ")
    signal_strengths.append(signal)
    if command[0] == "noop":
        rangeend = 2
    else:
        rangeend = 3
    for p in range(1, rangeend):
        cycles += 1
        pixel = (cycles)%40
        line = math.floor((cycles)/40)

        if p == 2:
            signal += int(command[1])
            signal_strengths.append(signal)
        first = signal - 1
        last = signal + 1
        if first < 0:
            first = 39
            line -= 1
        if last > 39:
            last = 0
            line += 1
        if pixel in [first, signal, last]:
            display[line][pixel] = "#"

check_values = [20, 60, 100, 140, 180, 220]
total = 0
for each in check_values:
    # print(f"{signal_strengths[each-1]} | {signal_strengths[each]} | {signal_strengths[each]}")
    total += each * signal_strengths[each]
print(total)
# 14060

show_display(display)
## PAPKFKEJ

Advent of Code 2022, Day 9

Things are getting tricky here now on Day 9, though not excessively hard. Just hard-ish. Today’s puzzle involves rope simulations. The data set consists of movement for the head of the rope and the end of the rope (and subsequent segments) follows rules that essentially keep the tail near the head. For example, if the head moves right 4 spaces, the tail follows, moving right 4 spaces. The tally was how many locations on a grid did the tail visit at least once.

The movement part was mostly simple, first create a function to move the head around. It wasn’t necessary, but I saved the head coordinates into a list. It was useful for verifying my code against the sample data. Moving the head was easy. Moving the tail was trickier. My movement function evolved quite a bit, it was originally quite a few messy if statements. But as i worked through the problem, it simplified down more and more until it was one movement function, called for the x or y if needed.

The diagonal movement was tricky, though, until I realized it was easiest to just, always align the opposing x or y coordinate. Let me try to clear up what I am saying. Straight Left, Right, Up, Down, movement is easy. When the head is opposite of the tail diagonally, by 1 each way, the tail won’t move. But if the head moves again, and now it’s 2 away along say, the Up direction, in addition to the tail moving up one, it also needs to move over left or right to align with the head.

To solve this, it just, does the alignment every time. In regular movement, this doesn’t do anything, since it’s already aligned, if it’s a diagonal movement, it doesn’t it’s job.

Each time the tail moves, it’s coordinates are also dropped into an array to track it’s movements. The tally needed only wants unique coordinates, so keeping track of where it’s been allows for easily checking for new coordinates and incrementing the counter.

Part 2 mixed things up a bit in a predictable way, multiple segments, before the tail. Same rules for movement. The code below could be simplified down to combine part 1 and 2, but I opted to just copy and paste for simplicity. The base loop is the same, though I removed the unneeded head tracking list. The main difference is that instead of a head and tail position, it gets fed a list of coordinates, for each segment, that it loops through every move of the head.

And it got close. Super close. Three away close!

the code worked for the sample given with an answer of 36. It worked for my original 1 segment rope, if i cut the starting array down to 2 coordinates. But not for the fill puzzle input.

I could see the problem, but not quite the solution. The issue was that sometimes, it was going to need to move diagonally. And it was fixed by adding a simple extra if statement.

if abs(hpos[0]-xpos) > 1 and abs(hpos[1]-ypos) > 1:
    xpos = move_pos(hpos[0], xpos)
    ypos = move_pos(hpos[1], ypos)

If BOTH coordinates are large, move them both, instead of one or the other. And the correct answer was revealed!

with open("Day09Input.txt") as file:
    data = file.read()

moves = data.split('\n')

positions = [[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0],[0,0]]
head_pos = [0,0]
tail_pos = [0,0]

head_moves = [head_pos]
tail_moves = [tail_pos]
long_tail_moves = [positions[len(positions)-1]]

tail_counter = 1
long_tail_counter = 1

def move_pos(a,b):
    if a - b > 0:
        return b+1
    if a - b < 0:
        return b-1
    return b

def move_head(dir,hpos):
    if dir == "R":
        return [hpos[0]+1,hpos[1]]
    if dir == "L":
        return [hpos[0]-1,hpos[1]]
    if dir == "U":
        return [hpos[0],hpos[1]+1]
    if dir == "D":
        return [hpos[0],hpos[1]-1]
    return pos

def move_tail(hpos,tpos):
    xpos = tpos[0]
    ypos = tpos[1]
    if abs(hpos[0]-xpos) > 1 and abs(hpos[1]-ypos) > 1:
        xpos = move_pos(hpos[0], xpos)
        ypos = move_pos(hpos[1], ypos)
    if abs(hpos[0]-xpos) > 1:
        ypos = hpos[1]
        xpos = move_pos(hpos[0], xpos)
    if abs(hpos[1]-ypos) > 1:
        xpos = hpos[0]
        ypos = move_pos(hpos[1], ypos)
    return [xpos, ypos]

# Part 1
for move in moves:
    turn = move.split(" ")
    for i in range(int(turn[1])):
        head_pos = move_head(turn[0], head_pos)
        head_moves.append(head_pos)
        tail_pos = move_tail(head_pos, tail_pos)
        if tail_pos not in tail_moves:
            tail_counter += 1
        tail_moves.append(tail_pos)

# Part 2
for move in moves:
    turn = move.split(" ")
    for i in range(int(turn[1])):
        positions[0] = move_head(turn[0], positions[0])
        for i in range(1,len(positions)):
            positions[i] = move_tail(positions[i-1], positions[i])
        if positions[len(positions)-1] not in long_tail_moves:
            long_tail_counter += 1
        long_tail_moves.append(positions[len(positions)-1])



# print(head_moves)
# print(tail_moves)
print(tail_counter)
#5902

#print(long_tail_moves)
print(long_tail_counter)
# high 11271
# high 2448
# low 2395

## 2445

Advent of Code 2022, Day 8

Today’s puzzle involved a forest of trees, and evaluating the heights of trees in that forest. For the sake of coding simplicity, the trees are a nice grid, which makes it an easy 2 dimensional matrix. This was my biggest hang up in designing a solution, Because Python handles 2 dimensional matrices as a “list of lists”. Which means often, the x and y coordinates need “flipped” when referenced, which often screws me up. This is because and loops will run down the rows, then the columns, that is, it will run down down the y axis then the x axis.

Technically, I don’t think it actually matters from a programmatic perspective, but it makes it tricky to logic out.

Otherwise the process is just running up and down in either direction to see if any tree is taller than the target tree. If it is not, then the tree is “Visible”. A tree only needs to be “Visible” from one of the 4 cardinal directions, to be counted.

The only other tricky part for part 1, is that all of the sides are considered “visible. The first instinct is to just take the length of the sides times 4, and add it to the total, except this means counting the corners twice. So you either need to subtract 4 or take the length-1 times 4.

Part 2 game me a fair amount of trouble, and after a lot of troubleshooting, it ended up being kind of a stupid issue. You need to check each tree, to see how many trees they can see, before hitting a taller tree (that they can’t see beyond). I left them in, but my troubleshooting is all those commented out print statements

# print(tree_grid[y][i] + " " + tree_grid[y][x])

Because I took the sample data, and checked to make sure it was stepping through each set properly. One by one, for each cardinal direction. And I was close and then not close, and I tried adding +1 to ranges and maybe I need this to start here instead of there an finally I found I was doing <= instead of just <, which was giving me bad results. I could have sworn the puzzle said they can see trees past those of equal height, but nope. Removing those equals signs fixed it.

Also, I am sure this code could be refactored down to be less repetitious, but it works fine now, no need to break it. I actually started working through it in a more compact method that used one function for each direction but I started to get loss so I just expanded it out.

with open("Day08Input.txt") as file:
    data = file.read()

tree_grid = data.split('\n')

leny = len(tree_grid)-1

tall_total = 0

def check_west(x,y):
    for each in range(0, x):
        if tree_grid[y][x] <= tree_grid[y][each]:
            return False
    return True

def check_east(x,y):
    for each in range(x+1,len(tree_grid)):
        if tree_grid[y][x] <= tree_grid[y][each]:
            return False
    return True

def check_north(x,y):
    for each in range(0, y):
        if tree_grid[y][x] <= tree_grid[each][x]:
            return False
    return True

def check_south(x,y):
    for each in range(y + 1, len(tree_grid)):
        if tree_grid[y][x] <= tree_grid[each][x]:
            return False
    return True

def scenic_score(x,y):
    east_score = 0
    west_score = 0
    north_score = 0
    south_score = 0

    for i in range(x+1,len(tree_grid)):
        if tree_grid[y][i] < tree_grid[y][x]:
            east_score += 1
        else:
            east_score += 1
            break
    for i in range(y+1, len(tree_grid)):
        if tree_grid[i][x] < tree_grid[y][x]:
            # print(tree_grid[i][x] + " " + tree_grid[y][x])
            south_score += 1
        else:
            # print(tree_grid[i][x] + " " + tree_grid[y][x])
            south_score += 1
            break
    for i in reversed(range(0, x)):
        if tree_grid[y][i] < tree_grid[y][x]:
            # print(tree_grid[y][i] + " " + tree_grid[y][x])
            west_score += 1
        else:
            # print(tree_grid[y][i] + " " + tree_grid[y][x])
            west_score += 1
            break
    for i in reversed(range(0, y)):
        if tree_grid[i][x] < tree_grid[y][x]:
            # print(tree_grid[i][x] + " " + tree_grid[y][x])
            north_score += 1
        else:
            # print(tree_grid[i][x] + " " + tree_grid[y][x])
            north_score += 1
            break
    # print(f"{north_score} * {west_score} * {east_score} * {south_score}")
    return east_score * south_score * west_score * north_score

high_score = 0
for y in range(1, len(tree_grid[0])-1):
    for x in range(1, len(tree_grid)-1):
        if check_west(x,y) or check_east(x,y) or check_north(x,y) or check_south(x,y):
            tall_total += 1
        score = scenic_score(x,y)
        if score > high_score:
            high_score = score


print(tall_total+((len(tree_grid))*4)-4)
# 2007 High
# 1991 High
# 1859 Correct
print(high_score)
# 332640

Advent of Code 2022, Day 7

So, this one was the first one so far that was tricky. Even though it’s not really that hard, I had actually already planned it out for the most part from just reading the prompt. You essentially get a series of Command Line commands and files with sizes, and have to move around a file system adding up numbers (file sizes).

I built a dictionary to track the total file size for the directories, and a list to keep track of where I was in the directory tree. Easy easy so far. Also, everything worked will on the sample data.

But I got stuck, because my totals were not matching. I tried like a dozen different slight modification to the method, and manually parsed through chunks of print statement results. Everything SEEMED to be in order here. Eventually I even went to Reddit to find someone’s completed project to see what number I was shooting for, because sometimes I’m off by a straight forward amount, and the solution becomes blatantly obvious.

This was not the case, BUT the Part 2 solution I got from the other person’s code, was in my results. I had no idea what Part 2 was, but clearly I was getting good data, because the answer was already present in my data.

Eventually I used the other person’s solution to unlock Part 2, which I solved pretty quickly, which led me to believe even more that my process for part 1 was good.

I decided to make one additional modification to my code, in how it handled keys for the directory dictionary. Instead of “Directory: Size” I modified it so it was “RootDirectoryDirectoryDirectory(etc): size.

And it worked.

I was getting the right answer.

I suspect, the issue is that the directory names repeat within the folder structure, which means that when it was supposed to add to “Directory/Directory/Directory” it was instead adding to some previously established “OtherDirectory/OtherDirectory/Directory”.

Confused yet?

Anyway, here is my code, and it works, for both solutions.

with open("Day07Input.txt") as file:
    data = file.read()

split = data.split('\n')
tree_dict = {"/": 0}
current_dir = []

for each in split:
    cl = each.split(" ")
    if cl[0] == "$":
        if cl[1] == "cd":
            if cl[2] == "/":
                current_dir = ["/"]
            elif cl[2] == "..":
                current_dir.pop()
            else:
                current_dir.append(cl[2])
    elif cl[0] == "dir":
        tree_dict["".join(current_dir)+cl[1]] = 0
    else:
        for tree_walker in range(0,len(current_dir)):
            tree_dict["".join(current_dir[0:tree_walker+1])] += int(cl[0])
    # print(current_dir)
    # print(files)

# print(tree_dict)

space_needed = 30000000 - (70000000-tree_dict['/'])
size_to_delete = tree_dict["/"]
total_size = 0
for key in tree_dict.keys():
    if tree_dict[key] <= 100000:
        total_size += tree_dict[key]
    if tree_dict[key] > space_needed and tree_dict[key] < size_to_delete:
        size_to_delete = tree_dict[key]

print(total_size)
# 6199378 high
# 1048940 low
# 1145908 low

print(size_to_delete)

##Part 1: 1582412
##Part 2: 3696336