Maker

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

Advent of Code 2022, Day 6

Day 6 – Fixing the Communicator

I’m not real sure what’s up here, but today’s project was easy. Like… stupidly easy. Maybe it’s just something better suited to how Python Handles data? The Part 2 was even easier. It literally just involved duplicating the same function, changing one number, and running the code.

The Problem Part 1:

As you move through the dense undergrowth, one of the Elves gives you a handheld device. He says that it has many fancy features, but the most important one to set up right now is the communication system.

However, because he’s heard you have significant experience dealing with signal-based systems, he convinced the other Elves that it would be okay to give you their one malfunctioning device – surely you’ll have no problem fixing it.

As if inspired by comedic timing, the device emits a few colorful sparks.

To be able to communicate with the Elves, the device needs to lock on to their signal. The signal is a series of seemingly-random characters that the device receives one at a time.

To fix the communication system, you need to add a subroutine to the device that detects a start-of-packet marker in the datastream. In the protocol being used by the Elves, the start of a packet is indicated by a sequence of four characters that are all different.

The Problem Part 2:

Your device’s communication system is correctly detecting packets, but still isn’t working. It looks like it also needs to look for messages.

A start-of-message marker is just like a start-of-packet marker, except it consists of 14 distinct characters rather than 4.

So, yeah, the input is a long ass string of garbled characters. For part 1, it’s a simple matter of running along the string in 4 character chunks, and using count() to see if all 4 characters are unique. For Part 2, it’s literally the same thing, except it’s checking 14 character strings instead of 4.

The hardest part was figuring out how much to add to the output to make sure it was int he correct position, because I was off by one, because my money brain frequently gets confused on if I am counting from 0 or counting from 1.

from Day06Input import *

def check_string(string):
    for n in string:
        # print(n)
        if string.count(n) > 1:
            return False
    return True

def check_signal(signal):
    for i in range(0,len(signal)-3):
        if check_string(signal[i:i+4]):
            return i+4

def check_message(signal):
    for i in range(0,len(signal)-3):
        if check_string(signal[i:i+14]):
            return i+14

print(check_signal(signal))
# Low (Probably by 1
#1080 - Yep!
print(check_message(signal))
# 3645

Advent of Code 2022, Day 5

Day 05 – Moving Crates

The Problem Part 1:

The expedition can depart as soon as the final supplies have been unloaded from the ships. Supplies are stored in stacks of marked crates, but because the needed supplies are buried under many other crates, the crates need to be rearranged.

The ship has a giant cargo crane capable of moving crates between stacks. To ensure none of the crates get crushed or fall over, the crane operator will rearrange them in a series of carefully-planned steps. After the crates are rearranged, the desired crates will be at the top of each stack.

The Elves don’t want to interrupt the crane operator during this delicate procedure, but they forgot to ask her which crate will end up where, and they want to be ready to unload them as soon as possible so they can embark.

They do, however, have a drawing of the starting stacks of crates and the rearrangement procedure (your puzzle input).

After the rearrangement procedure completes, what crate ends up on top of each stack?

And I guessed what Part 2 would be, before it was even revealed:

Some mud was covering the writing on the side of the crane, and you quickly wipe it away. The crane isn’t a CrateMover 9000 – it’s a CrateMover 9001.

The CrateMover 9001 is notable for many new and exciting features: air conditioning, leather seats, an extra cup holder, and the ability to pick up and move multiple crates at once.

I’m going to throw the sample input in here as well, because getting through this was the hardest part.

    [D]    
[N] [C]    
[Z] [M] [P]
1   2   3

move 1 from 2 to 1
move 3 from 1 to 3
move 2 from 2 to 1
move 1 from 1 to 2

It’s essentially, two inputs one file.   A “drawing” of the stack, and a series of moves.  Splitting these up was simple enough, there is a double space, and split() works on “\n\n”.  What was hard, was manipulating the Crate Stack drawing into a list of lists so it was easy to work with on the moves function.

I’ll post the whole code, but I want to look at this function, because it was the hardest part and the most interesting thing here.

def pivot(crates):
    crates.pop(-1)
    processed = []
    for row in crates:
        row = row.replace('    ', ' [ ]')
        # print(len(row))
        while len(row) < len(crates[-1]):
            row += ' [ ]'
        row = row[1:-1].split('] [')
        # print(row)
        processed.append(row)
    # print(processed)
    return list(zip(*processed[::-1]))

What I am looking for, is a list of lists, for each “stack”.  The problem is, my input is “vertical” instead of “horizontal” and it has gaps.  I considered that there may be a way to do this with Pandas and Data Frames, but a lot of these puzzles really feel like the fun part is solving them without a bunch of complicated imports.  

The first step is to remove the bottom row, it’s just column labels, I don’t care about that part.

After a lot of consideration for how to handle the “blanks” I realized the best way was to convert them into “Blank Crates”.  Which is where the “row = row.replace(‘    ‘, ‘ [ ]’)” section comes in.  I also found that for the pivot later, I would need to fill in any blank spaces at the end of the rows as well, which si where the following while loop comes in.  

With the array filled in “fully” with blanks, I can straight split each row on “] [” and get a list, which is appended to “processed” as a fresh rwo, giving me a list of lists, but it’s still veetical.  I went out looking for a “pivot” function.  For anyone not familiar with this term, a super layman explanation is, a Pivot Table, is essentially a new table, based on values of an old table.  It’s been ‘Pivoted”.  A list of lists, is essentiallyy just “a table” of data,  A series of rows and columns.   All I want to do is literally pivot it so X becomes Y, because it makes things easier to “move crates” later with split() and pop() functions.  What I found was this:

list(zip(*processed[::-1]))

That handy Zip function again, which will basically just, do what I want.  

The only other real problem I had with this puzzle was on Part 2.  I tried several methods I found online, but I could not get a second copy of my original list.  It seems Python does some “Screwy Bullshit” with it’s lists where copies are not copies.  I kept getting errors trying to run my Part 2 code, index out of range.  Well, it was starting with the modified version of the original crates list.  I tried crates2 = crates[:], and crates2 = crates.copy() and crates2 = copy.copy() and nothing actually did what I needed.  

So I just, commented out the Part 1 code so it wouldn’t run.

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

split_data = data.split('\n\n')
crates = split_data[0].split('\n')
moves = split_data[1].split('\n')

def pivot(crates):
    crates.pop(-1)
    processed = []
    for row in crates:
        row = row.replace('    ', ' [ ]')
        # print(len(row))
        while len(row) < len(crates[-1]):
            row += ' [ ]'
        row = row[1:-1].split('] [')
        # print(row)
        processed.append(row)
    # print(processed)
    return list(zip(*processed[::-1]))

def drop_blanks(crates):
    de_blanked = []
    for crate in crates:
        row = [i for i in crate if i != ' ']
        de_blanked.append(row)
    return de_blanked

def move_crates(crate_move, moves):
    for move in moves:
        steps = move.split(" ")
        how_many = int(steps[1])
        from_stack = int(steps[3])-1
        to_stack = int(steps[5])-1
        for i in range(0,how_many):
            # print(crate_move[from_stack])
            # print(crate_move[to_stack])
            crate_move[to_stack].append(crate_move[from_stack].pop())
        #print(steps)
    return crate_move

def move_crates_in_stacks(crates_stack, moves):
    for move in moves:
        steps = move.split(" ")
        how_many = int(steps[1])
        from_stack = int(steps[3])-1
        to_stack = int(steps[5])-1
        #print(crates_stack[from_stack])
        move_list = crates_stack[from_stack][-how_many:]
        #print(crates_stack[to_stack])
        for i in range(how_many):
            crates_stack[from_stack].pop()
            crates_stack[to_stack].append(move_list[i])
        #print(steps)
    return crates_stack

crates = pivot(crates)
crates = drop_blanks(crates)
#Part 1
#moved = move_crates(crates, moves)
moved2 = move_crates_in_stacks(crates, moves)

print(crates)
#print(len(crates))
#print(moves)

#Part 1
# for each in moved:
#     print(each[-1])
#svfdLGLWV

for each in moved2:
    print(each[-1])
#DCVTCVPCL