Advent of Code 2022, Day 13

Have I ever mentioned before how much I hate Recursion?

So, I feel like I mentioned on a previous Advent of Code post, half the problem of these puzzles is figuring out how to massage the input. Which I started to work with until I found the eval() function, which I don’t recall using before. But it basically will take something like a string that looks like a list, say, “[2,[4,5,6]]” and make it into a list of lists. Which solved the first problem I had.

Then there was the checks itself. The puzzle was a series of lists full of lists and integers, that needed to be sorted based on some criteria. It basically amounts to a series of if checks, if the data is a list or an int and what to do, if the lengths are the same or different, if one value is larger than the other. Except it can be lists in lists, hence the need for recursion. I felt like I was really close, but then scrapped that for a new approach. Then I got stuck again, then I realized I needed to loop through the internal list. Everything eventually lined up for part 1 nicely.

On to Part 2. Which basically amounts to, using the algorithm on the entire list, instead of just pairs.

I was actually a bit disappointed because I was sure I had come up with a clever way to solve this without the sorting algorithm. I left it in the code, but it’s not used. Here it is anyway.

## Not Used But This really feels like it should have worked.
def decoder(decode_list):
    new_list = []
    for each in decode_list:
        each = each.replace("[]", "0")
        each = each.replace("[", "")
        each = each.replace("]", "")
        each = each.replace(",", "")
        new_list.append(int(each[0]))
    new_list.sort()
    print(new_list)
    print((new_list.index(6)+1)*(new_list.index(2)+1))

The idea was, that I would flatten each list out to an integer, then sort the data that way. The target values needed were simply, 2 and 6. The initial sort put 2 and 6 at basically positions 2 and 6. because 2 is less than 200 when sorting. So it dawned on me, that 2 and 6, would always be the “first” at the “start of the 2s” and “start of the 6s”. So the I just added the first digit to the list, then sorted that, and took the first 2 and first 6. And it still didn’t work.

Figures it wouldn’t be that simple.

While contemplating using nested for loops, I decided to check some other solutions, and found something I had not used before, “cmp_to_key”. After reading up on it, it seems it can be used with the sort function to generate sorts based on a key value returned from a function.

So I modified my sort unction to use +1, -1, and 0 instead of True and False.

Aaaaand, it still didn’t sort, it wasn’t sorting. I had forgotten that I needed to use eval() on each entry, to turn it into Lists instead of Strings. My sort wasn’t working because it doesn’t work on Strings. So I corrected that and bam! Working.

from functools import cmp_to_key

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

split_data = data.split("\n\n")
decode_data = []
for line in data.replace("\n\n", "\n").split("\n"):
    decode_data.append(eval(line))

def compare_lists(left,right):
    # print(left)
    # print(right)

    if isinstance(left, int) and isinstance(right, int):
        # print(f"{left} {right}")
        if left < right:
            return 1
        elif left > right:
            return -1
        return 0

    if isinstance(left, list) and isinstance(right, list):
        for value in range(min(len(left), len(right))):
            check_value = (compare_lists(left[value], right[value]))
            # print(f"{left[value]} {right[value]}")
            # print(check_value)
            if check_value != 0:
                return check_value

        if len(left) < len(right):
            return 1
        elif len(left) > len(right):
            return -1
    if isinstance(left, int) and isinstance(right, list):
        return compare_lists([left], right)
    if isinstance(left, list) and isinstance(right, int):
        return compare_lists(left, [right])

    return 0

## Not Used But This really feels like it should have worked.
def decoder(decode_list):
    new_list = []
    for each in decode_list:
        each = each.replace("[]", "0")
        each = each.replace("[", "")
        each = each.replace("]", "")
        each = each.replace(",", "")
        new_list.append(int(each[0]))
    new_list.sort()
    print(new_list)
    print((new_list.index(6)+1)*(new_list.index(2)+1))

index_sum = 0
for i in range(len(split_data)-1):
    set1 = split_data[i].split("\n")[0]
    set2 = split_data[i].split("\n")[1]

    match = compare_lists(eval(set1), eval(set2))
    # print(match)

    if match == 1:
        index_sum += (i+1)


print(index_sum)
# 6373 Too high
# 5997 Too low
# 6187

decode_data.append([[2]])
decode_data.append([[6]])
#decoder(decode_data)
decode_data.sort(key=cmp_to_key(compare_lists), reverse=True)
# for each in decode_data:
#     print(each)
print((decode_data.index([[2]])+1)*(decode_data.index([[6]])+1))

# 23520

Advent of Code 2022, Day 12

So, day 12, you get an elevation map, and you get to run a path-finding algorithm on it to find the shortest path up the hill.

That sounds kind of complicated.

So I did it with the best computer I have available, my mind. And Microsoft Word, and some color coded path markers. I did do a bit of black outs on obvious dead ends so my final map looks like some sort of government document but I got the answer. It probably took me less time than it would have to figure out and write code to do it too. I started after finishing breakfast, put on a podcast on the headphones and a half hour later, I had the map.

I did have a brain fart that screwed me up, For some reason I was using the Upper Left corner as “Start”. Start was actually the big fat “S” in the middle of the first column.

Anyway, no code, but here is an image of my finished map.

100 Days of Python, Project 083 – Tic-Tac-Toe #100DaysofCode

Writing this write up took considerably longer than actually writing the code.

I saw a post once commenting how the world doesn’t need another version of Tic-Tac-Toe made in Python. Well that’s too bad, because here comes another one! I keep telling myself I want to make a slightly more detailed run through some of my code writing, just for the sake of “This is the process,” so let’s see if I can make a go of it for this round. Funny enough, this isn’t the first time I’ve set out to make TicTacToe on my own accord, I once started working out doing it in C++ once, mostly because I wanted to see if I could build a super tough algorithm for a computer AI playing TicTacToe.

This whole post will contain a whole lot of somewhat repetitious and incremental Python code, but maybe it will be helpful to some newbie coders to get a better idea of how to step through what you’re writing and how to break up and plan different parts of your code.

The first step here, is to decide which method to use to create this little game. I could do it with Text but that feels ugly and boring. I could probably make a web version with Flask, but that feels overly complicated. That leaves Tkinter or Turtle. I opted for Turtle. I like Turtle, it has a fun sort of retro feel to it, and it’s simple enough to use.

This post is Extremely Long and full of code, so I’m putting ti behind a Read More, and here it is!

—– Read More —–: 100 Days of Python, Project 083 – Tic-Tac-Toe #100DaysofCode Read More

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