December 2022

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

Sunday 2022-12-11 – Link List

Blogging Intensifies Link List for Sunday 2022-12-11

10-Dec-2022 – Your Action Figure Of The Year

09-Dec-2022 – Castlevania DLC Comes to Dead Cells Indie Game in 2023

08-Dec-2022 – The Super Mario Bros. Movie’s Clip Highlights Mushroom Kingdom

10-Dec-2022 – Mean Girls musical casts Angourie Rice, Auli’i Cravalho and more

09-Dec-2022 – Transformers: Reactivate video game announced with cinematic trailer

11-Dec-2022 – Joker 2 First Photo Released

08-Dec-2022 – [Epic Games] Saints Row IV Re-Elected | Wildcat Gun Machine (Free/100% off)

08-Dec-2022 – Dead Cells is getting paid Castlevania DLC next year

08-Dec-2022 – Minecraft’s bizarre end poem never owned by Mojang or Microsoft, writer claims

07-Dec-2022 – Fortnite Chapter 4 adds the Witcher, Doom Slayer, and a whole new island

07-Dec-2022 – Valheim’s Mistlands update now lets you wield magic in the fog

07-Dec-2022 – Dwarf Fortress review: the legendary colony sim gets a welcome facelift for Steam

05-Dec-2022 – Retro Game of the Year Awards 2022

09-Dec-2022 – Taylor Swift is set to direct a feature film, ‘FYI’

09-Dec-2022 – Carly Rae Jepsen has released a new theme for Hello Kitty: Super Style!

08-Dec-2022 – Gorillaz have shared their brand new single, ‘Skinny Ape’

08-Dec-2022 – Taylor Swift has shared behind-the-scenes footage from her award-winning music video, ‘All Too Well’

06-Dec-2022 – Dwarf Fortress review – a grand chronicle of inevitable disaster

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