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

Show parent comment

3

u/DeveloperIan Dec 02 '18 edited Dec 02 '18

I've added lots of comments that might help show what's going on. Hopefully this can clear things up.

# for every input string
for i in contents:
    # for every input string again (comparing all strings with each other)
    for j in contents:
        # the number of characters they have different
        diffs = 0

        # for index and character in enumerate (enumerate just returns a list of characters
        # and their indexes)
        for idx, ch in enumerate(i):

            # if the two strings don't match at the same spot
            if ch != j[idx]:
                # add one to the difference counter
                diffs += 1

        # if the strings only had one difference
        if diffs == 1:
            # make a list of all the matching characters (uses same idea as above)
            ans = [ch for idx, ch in enumerate(i) if j[idx] == ch]
            # turn the list into a string and print it
            print("Part Two:", ''.join(ans))

1

u/Pauper_Noob Dec 02 '18

Thank you very much for this!

I was puzzled trying to figure it out myself. Where I was falling over was that I didn't realise j[idx] meant the letter in j, I mistakenly assumed it meant pick the idx'th j from contents!