AdventOfCode2022

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    

Advent of Code 2022, Day 2

Day 2 – Cheating at Rock Paper Scissors

The Problem Part 1:

The Elves begin to set up camp on the beach. To decide whose tent gets to be closest to the snack storage, a giant Rock Paper Scissors tournament is already in progress.

Rock Paper Scissors is a game between two players. Each game contains many rounds; in each round, the players each simultaneously choose one of Rock, Paper, or Scissors using a hand shape. Then, a winner for that round is selected: Rock defeats Scissors, Scissors defeats Paper, and Paper defeats Rock. If both players choose the same shape, the round instead ends in a draw.

Appreciative of your help yesterday, one Elf gives you an encrypted strategy guide (your puzzle input) that they say will be sure to help you win. “The first column is what your opponent is going to play: A for Rock, B for Paper, and C for Scissors. The second column–” Suddenly, the Elf is called away to help with someone’s tent.

The second column, you reason, must be what you should play in response: X for Rock, Y for Paper, and Z for Scissors. Winning every time would be suspicious, so the responses must have been carefully chosen.

The winner of the whole tournament is the player with the highest score. Your total score is the sum of your scores for each round. The score for a single round is the score for the shape you selected (1 for Rock, 2 for Paper, and 3 for Scissors) plus the score for the outcome of the round (0 if you lost, 3 if the round was a draw, and 6 if you won).

The Problem Part 2:

The Elf finishes helping with the tent and sneaks back over to you. “Anyway, the second column says how the round needs to end: X means you need to lose, Y means you need to end the round in a draw, and Z means you need to win. Good luck!”

So, the simplest way to deal with the input file, which were combinations of ABC and XYZ, is a dictionary, with the possible scores.  As mentioned earlier, a lot of of these are running a pile of data through a loop, and often the actual puzzle, is figuring out the simplest way to loop through and match values.  This could have been done with a ton of IF/Else cases or even a Switch style statement as well.  The data doesn’t change so both Part 1 and Part 2 could be calculated at once pretty easily.

with open("Day02Input.txt") as file:
        games = file.read()

rps = games.split("\n")

scores_dict1 = {"A X": 4,
                "A Y": 8,
                "A Z": 3,
                "B X": 1,
                "B Y": 5,
                "B Z": 9,
                "C X": 7,
                "C Y": 2,
                "C Z": 6, }

scores_dict2 = {"A X": 3,
                "A Y": 4,
                "A Z": 8,
                "B X": 1,
                "B Y": 5,
                "B Z": 9,
                "C X": 2,
                "C Y": 6,
                "C Z": 7, }

total1 = 0
total2 = 0

for each in rps:
    total1 += scores_dict1[each]
    total2 += scores_dict2[each]

print(total1)
print(total2)

Advent of Code 2022, Day 1

Another year, another Advent of Code. Though I kind of skipped last year. I think I may have been too busy or something. I do enjoy doing these puzzles, though they aren’t really “code projects”.  Each day is just a puzzle, that is solved with math.  Most of the problem, is figuring out what exactly is being asked.  The other part is just, figuring out how to format the data set you are given.  A lot of these are kind of repetitive, open your data file, read it in, convert it to a useful format, loop through the data, performing some action, and output some sort of total.

For this year’s theme, Santa’s Elves are taking a journey to a magical grove to collect food for the reindeer.

Day 1 – Elf Food Calories

The Problem Part 1:

The jungle must be too overgrown and difficult to navigate in vehicles or access from the air; the Elves’ expedition traditionally goes on foot. As your boats approach land, the Elves begin taking inventory of their supplies. One important consideration is food – in particular, the number of Calories each Elf is carrying (your puzzle input).

The Elves take turns writing down the number of Calories contained by the various meals, snacks, rations, etc. that they’ve brought with them, one item per line. Each Elf separates their own inventory from the previous Elf’s inventory (if any) by a blank line.

In case the Elves get hungry and need extra snacks, they need to know which Elf to ask: they’d like to know how many Calories are being carried by the Elf carrying the most Calories.

The Problem Part 2

By the time you calculate the answer to the Elves’ question, they’ve already realized that the Elf carrying the most Calories of food might eventually run out of snacks.

To avoid this unacceptable situation, the Elves would instead like to know the total Calories carried by the top three Elves carrying the most Calories. That way, even if one of those Elves runs out of snacks, they still have two backups.

So, each day consists of a Part 1 and a Part 2.  Generally speaking, each of these two parts is semi related, and can be completed with most of the same code. This one is simple enough, split the list up by lines, then split it into each elf’s calories, sort the list so the highest valies are at the front and print those three values out.  Part 1 only needs the highest, Part 2 needs the next two.

with open("Day01Input.txt") as file:
    calories = file.read()

calories = calories.replace("\n"," ")
elves = [each.split(" ") for each in calories.split("  ")]
totals = []

for each in elves:
    total = 0
    for i in each:
        total += int(i)
    totals.append(total)
 
totals.sort(reverse=True)
print(totals[0]+totals[1]+totals[2])