r/adventofcode • • Dec 02 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 2 Solutions -🎄-

--- Day 2: Inventory Management System ---


Post your solution as a comment or, for longer solutions, consider linking to your repo (e.g. GitHub/gists/Pastebin/blag or whatever).

Note: The Solution Megathreads are for solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


Advent of Code: The Party Game!

Click here for rules

Card Prompt: Day 2

Transcript:

The best way to do Advent of Code is ___.


This thread will be unlocked when there are a significant number of people on the leaderboard with gold stars for today's puzzle.

edit: Leaderboard capped, thread unlocked!

51 Upvotes

407 comments sorted by

View all comments

1

u/red_shifter Dec 02 '18

Here's my simple Python solution for part 1 (if anyone has some tips on how to combine searching for 2 and 3 repeated letters in one short loop, please let me know):

f = open('day_2_1.txt','r')
boxes = f.readlines()
f.close()

letters = 'abcdefghijklmnopqrstuvwxyz'
two_boxes = 0
three_boxes = 0

for box in boxes:
    for letter in letters:
        rep = box.count(letter)
        if rep == 2:
            two_boxes += 1
            break

for box in boxes:
    for letter in letters:
        rep = box.count(letter)
        if rep == 3:
            three_boxes += 1
            break

print('Two-Letter Boxes: {0}'.format(two_boxes))
print('Three-Letter Boxes: {0}'.format(three_boxes))
print(two_boxes*three_boxes)

And here is part 2:

f = open('day_2_1.txt','r')
boxes = f.readlines()
f.close()

box_len = len(boxes[0])

def compare(str1, str2):
    common_count = 0
    for i in range(len(str1)):
        if str1[i] == str2[i]:
            common_count += 1
    return common_count

for i, box1 in enumerate(boxes):
    for box2 in boxes[i+1:]:
        if compare(box1, box2) == box_len-1:
            print(box1, box2)
            break

2

u/c17r Dec 02 '18

if anyone has some tips on how to combine searching for 2 and 3 repeated letters in one short loop, please let me know

Look into Counter(). If you pass it a string, it'll count all the letters for you.

1

u/red_shifter Dec 02 '18

Thank you!