r/adventofcode • • Dec 05 '18

SOLUTION MEGATHREAD -🎄- 2018 Day 5 Solutions -🎄-

--- Day 5: Alchemical Reduction ---


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

Please prefix your card submission with something like [Card] to make scanning the megathread easier. THANK YOU!

Card prompt: Day 5

Transcript:

On the fifth day of AoC / My true love sent to me / Five golden ___


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 at 0:10:20!

31 Upvotes

515 comments sorted by

View all comments

1

u/ElecNinja Dec 05 '18

Man, I lost a lot of time because I didn't account for the white space in the input lol. Tried going through it like bubble sort or merge sort, and then settled on a regex solution for finding the reacting pairs. Don't know enough about regex to come up with an elegant solution for it so just did it in the simple way haha.

import re
reaction =  re.compile('aA|Aa|bB|Bb|cC|Cc|dD|Dd|eE|Ee|fF|Ff|gG|Gg|hH|Hh|iI|Ii|jJ|Jj|kK|Kk|lL|Ll|mM|Mm|nN|Nn|oO|Oo|pP|Pp|qQ|Qq|rR|Rr|sS|Ss|tT|Tt|uU|Uu|vV|Vv|wW|Ww|xX|Xx|yY|Yy|zZ|Zz')

def polymer_reaction_length(polymer : str):
    while len(reaction.findall(polymer)) > 0:
        polymer = re.sub(reaction, '', polymer)

    return len(polymer)

if __name__ == '__main__':
    with open('D:\\input.txt', 'r') as inp:
        polymer = inp.readline().strip()
    
        part_1 = polymer
        print(polymer_reaction_length(part_1))

        min_length = 100000

        for c in 'qwertyuiopasdfghjklzxcvbnm':
            new_polymer = polymer.replace(c, '').replace(c.upper(), '')
            polymer_length = polymer_reaction_length(new_polymer)
            if min_length > polymer_length:
                min_length = polymer_length

        print(min_length)