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

Advent of Code 2022, Day 4

Day 4 – Cleaning Up The Landing Zone

The Problem Part 1:

Space needs to be cleared before the last supplies can be unloaded from the ships, and so several Elves have been assigned the job of cleaning up sections of the camp. Every section has a unique ID number, and each Elf is assigned a range of section IDs.

However, as some of the Elves compare their section assignments with each other, they’ve noticed that many of the assignments overlap. To try to quickly find overlaps and reduce duplicated effort, the Elves pair up and make a big list of the section assignments for each pair (your puzzle input).

Some of the pairs have noticed that one of their assignments fully contains the other. For example, 2-8 fully contains 3-7, and 6-6 is fully contained by 4-6. In pairs where one assignment fully contains the other, one Elf in the pair would be exclusively cleaning sections their partner will already be cleaning, so these seem like the most in need of reconsideration. In this example, there are 2 such pairs.

In how many assignment pairs does one range fully contain the other?

The Problem Part 2:

It seems like there is still quite a bit of duplicate work planned. Instead, the Elves would like to know the number of pairs that overlap at all.

These two problems use two seperate functions, but the same loop to solve both at once.  I’m particularly proud of my solution for checking on Overlap, though I’m not sure if it’s the best solution.  For example, with the sample data:

2-4,6-8
2-3,4-5
5-7,7-9
2-8,3-7
6-6,4-6
2-6,4-8

the first one 2-4, and 6-8, does not over lap at all, but in the 4th one, 2-8 completely contains 3-7.  What I used was simple math based logic, substrct the start numbers and end numbers.  With the lines 1 and 4, this would give:

2-6 = -4, 4-8 = -4
2-3 = -1, 8-7 = 1

Then, multiply each of these results together for each elf.

-4 * -4 = 16
-1 * 1 = -1

For all lines, if the result is greater than 0, it’s not 100% inclusive.  From the above, 16, is not, -1 is.  This is also true of line 5, which will result in 0.  A zero results if either the start or end are equal, which will always be completely inclusive.

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

worklist = data.split("\n")

def check_range(elves):
    work = elves.split(",")
    elf1 = work[0].split("-")
    elf2 = work[1].split("-")
    for i in range(int(elf1[0]),int(elf1[1])+1):
        if i in range(int(elf2[0]),int(elf2[1])+1):
            return 1
    return 0

def check_overlap(elves):
    work = elves.split(",")
    elf1 = work[0].split("-")
    elf2 = work[1].split("-")
    if (int(elf1[0])-int(elf2[0]))*(int(elf1[1])-int(elf2[1])) > 0:
        return 0
    return 1

total = 0
range_total = 0

for each in worklist:
    total += check_overlap(each)
    range_total += check_range(each)

print(total)
#485

print(range_total)
# 658 LOW
#857

Advent of Code 2022, Day 3

Day 3 – Sorting the Food Into Sacks

The Problem Part 1:

One Elf has the important job of loading all of the rucksacks with supplies for the jungle journey. Unfortunately, that Elf didn’t quite follow the packing instructions, and so a few items now need to be rearranged.

Each rucksack has two large compartments. All items of a given type are meant to go into exactly one of the two compartments. The Elf that did the packing failed to follow this rule for exactly one item type per rucksack.

The Elves have made a list of all of the items currently in each rucksack (your puzzle input), but they need your help finding the errors. Every item type is identified by a single lowercase or uppercase letter (that is, a and A refer to different types of items).

The list of items for each rucksack is given as characters all on a single line. A given rucksack always has the same number of items in each of its two compartments, so the first half of the characters represent items in the first compartment, while the second half of the characters represent items in the second compartment.

Part 2 Problem:

For safety, the Elves are divided into groups of three. Every Elf carries a badge that identifies their group. For efficiency, within each group of three Elves, the badge is the only item type carried by all three Elves. That is, if a group’s badge is item type B, then all three Elves will have item type B somewhere in their rucksack, and at most two of the Elves will be carrying any other item type.

The problem is that someone forgot to put this year’s updated authenticity sticker on the badges. All of the badges need to be pulled out of the rucksacks so the new authenticity stickers can be attached.

Additionally, nobody wrote down which item type corresponds to each group’s badges. The only way to tell which item type is the right one is by finding the one item type that is common between all three Elves in each group.

So, the actual input on a lot of these puzzles is a numerical value, for this problem, it wanted the totals for the Food ID and Badge IDs, based on 1-26 and 27-52, depending on the value.  The simple way of summing these is the list at the top.  Each value is just the index of that list.

I also have this really messy line for ” contents = [[each[:int(len(each)/2)],each[int(len(each)/2):]] for each in data.split(‘\n’)]” in there, to break up each line into a list of lists.  Split can’t be used because each line is just a long list of jumbled letters.  The next line uses a function that I came across looking for an easy way to group everyone up into blocks of 3 for the second part.  I found the “zip” function, which is pretty cool and I’ve used it later in another puzzle as well.

The original Part 1 version of this code just ran through the individual contents variable.  But when I added in Part 2, with the 3 Elf Groups, I modified it to run off of groups of 3, while still solving both problems at once.  The actual finding of the items and badges was not hard, it’s just checking to see if values of one string are in another string using a loop.  A List Comprehension would work too, but for simple loops like this I find them more readable.

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

letters = [
    'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o',
    'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D',
    'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S',
    'T', 'U', 'V', 'W', 'X', 'Y', 'Z']

contents = [[each[:int(len(each)/2)],each[int(len(each)/2):]] for each in data.split('\n')]

groups = zip(*[iter(contents)]*3)
def find_item(elf):
    for i in elf[0]:
        if i in elf[1]:
            return letters.index(i) + 1

def find_badge(group):
    elves = [group[0][0]+group[0][1],group[1][0]+group[1][1],group[2][0]+group[2][1]]
    for i in elves[0]:
        if i in elves[1] and i in elves[2]:
            return letters.index(i)+1

priority_sum = 0
badge_sum = 0

for each_group in groups:
    for elf in each_group:
        priority_sum += find_item(elf)
    badge_sum += find_badge(each_group)

print(priority_sum)
# 7526 Too Low
# 7826
print(badge_sum)
# 2577    

100 Days of Python, Project 082 – Personal Portfolio Website #100DaysofCode

This felt like an odd one, but probably still a good one to be included.  I also was kind of torn on if I even needed/wanted to actually “do” it.  This part is effectively already “Done”.  We created a GitHub.io site.  We created a Heroku based Blog (which I skipped in favor of doing it on my own server/host).  I also basically already have a portfolio website.  Right here, on this blog.  I post my projects, I write about them, etc etc.  I also have a pretty nice GitHub page, which is the best “programming portfolio” one can have.

So I was going to skip it initially, but instead, I opted to go with getting Flask to work on my web server, which was more of a hassle than I expected, but now, over time, I can start modifying that site to show case some of the things I’ve built.  Currently, it resides at https://joshmiller.net .  It’s nothing fancy as of this writing, just the bare bones of the Flask Blog built previously.  I did strip out the registration portion.  I really don’t need or want to deal with comments.  Sorry, @me on Mastodon instead.  I don’t really need a blog either, so don’t expect much going on there, but I want to keep it for now because I may use it to basically, blog about the blog.  I also want to build some new features over time to make it more full featured.  For starters, it needs a settings/admin page, to set things like the title and toggle comments on/off.  It also desperately needs an upload portal for images for use in blogs.

So what’s the point.  Well, for one, it has built in Authentication.  Which means I can build pages and tools that only I will ever have access to.  One I have been thinking of building would basically be a blog post form, that simultaneously posts to several social networks, using APIs.  Also, related to authenticating, the functional nature of these Flask Apps, means I can easily drop in say, the Top Ten Movies website, and have it show up at joshmiller.net/movies or something, just by adjusting some of the code.  And with the built in authentication, I can lock the world out from being able to edit my movies list.

I also, have been really looking for SOME use for that domain.  Though, I still may reconsider and move it all to a sub domain on this site.  I have not decided.  I already stopped using that domain for email and it essentially just… exists… now.

Anyway, I think it’s worth talking about how I got things going, because I had a hell of a time getting Apache to work nicely with Flask and WSGI.  And I looked into a lot of guides…. a LOT.

Honestly it’s been so many I will probably miss something here.  This is going to be a bit general and not nearly as hand holdey as it could be.  Chances are, if you can’t figure this out, you probably shouldn’t be doing it.  And chances are, you already have a web server with Apache going, so you kind of know what you’re doing.  The first step is to make sure Python is installed, and Python3, and the various needed imports, using pip3, not pip.

sudo apt-get install python3

sudo apt-get install python3-pip

If you need them.

Download your flask app to a folder /var/www/FlaskApp .  It should just be in the base here, but it can be elsewhere if you know what you’re doing.  Then run the main.py file.

python3 main.py

Fix any permissions issues, or, for now try sudo python3 main.py.  For everything it can’t find each run, do

sudp pip3 install <Package>

Eventually the main.py should run, and you can access your site at <ServerIP:5000>.  The truck now is getting Apache to work with it.  First you’ll want to install mod-wsgi then enable it.

sudo apt-get install libapache2-mod-wsgi python-dev

sudo a2enmod wsgi

Now, in the folder with main.py, the /var/www/FlaskApp folder, create a file called flaskapp.wsgi.

sudo nano flaskapp.wsgi

Inside this file, add the following.

#!/usr/bin/python

import sys

import logging

logging.basicConfig(stream=sys.stderr)

sys.path.insert(0,"/var/www/FlaskApp/")

from main import app as application

application.secret_key = 'Your Secret Key, it may Need to be the same as the one in main.py I am not sure'

application.root_path = '/var/www/FlaskApp'

Save that file.

Next create the site file for Apache to use.

sudo pico /etc/apache2/sites-available/YOUR_SiTE_FILE_NAME_CAN_BE_WHATEVER_MAKE_IT_MEANINGFUL.conf

Inside that file, add the following.  Please note, this file also contains settings that allow for SSL via Let’s Encrypt, which you should be running on your web server anyway.

<IfModule mod_ssl.c>

SSLStaplingCache shmcb:/var/run/apache2/stapling_cache(128000)

<VirtualHost *:443>

        ServerAdmin YOUR EMAIL HERE

        ServerName YOUR SITE DOMAIN OR SUBDOMAIN.DOMAIN HERE

        ServerAlias www.YOUR SITE DOMAIN HERE SO WWW REDIRECTS REMOVE FOR SUB DOMAINS

        WSGIScriptAlias / /var/www/FlaskApp/flaskapp.wsgi

        <Directory /var/www/FlaskApp/FlaskApp/>

          Order allow,deny

          Allow from all

        </Directory>

        ErrorLog ${APACHE_LOG_DIR}/error.log

        CustomLog ${APACHE_LOG_DIR}/access.log combined

# If you don't have Lets Encrypt you can probably dump this next section through <VirtualHost> Keep that

        Include /etc/letsencrypt/options-ssl-apache.conf

        Header always set Strict-Transport-Security "max-age=31536000"

        SSLUseStapling on

        Header always set Content-Security-Policy upgrade-insecure-requests

        # Lets Encrypt Folders below

        SSLCertificateFile /etc/letsencrypt/live/YOURSITEDOMAIN.com/fullchain.pem

        SSLCertificateKeyFile /etc/letsencrypt/live/YOURSITEDOMAIN.com/privkey.pem

</VirtualHost>

</IfModule>

Now, the most important thing to note here.  In every single guide I found, it included a section to alias the “Static” directory.  I got to a point where my site was working, but it was not loading CSS.  I fixed this by REMOVING this alias.  

I beleive that having “application.root_path = ‘/var/www/FlaskApp'” inside the wsgi file, confliced with the Alias.  But the application wasn’t running at all without “application.root_path = ‘/var/www/FlaskApp'”.  The end result, was a working blog site.  I could create a user, create new posts, leave comments, and everything looked as it should.  It’s working now though, at least, which was the goal.  I can polish it up over time.  

Like I mentioned previously, I am not sure what or how much I will post there.  I may actually completely remove the blog part of it.  I’m more interested in the admin/login functionality really.  I already have plenty of blogging outlets between this site and Mastodon, and using Tumblr more and probably a fresh new push at Lameazoid.com as well.  I don’t need this additional random blog at all.