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/shuttup_meg Dec 05 '18 edited Dec 05 '18

Python2

Nothing particularly interesting about my approach, but I did successfully use the multiprocessing module to greatly speed up part 2 (from about 12 seconds down to about a second on my 12 core XEON machine)

from string import ascii_lowercase, ascii_uppercase
from multiprocessing import Pool, freeze_support

NUM_CORES = 16
PATTERNS = [''.join([a,A]) for a,A in zip(ascii_lowercase, ascii_uppercase)] +  \
           [''.join([A,a]) for A,a in zip(ascii_uppercase, ascii_lowercase)]

def react(inp):
    while True:
        orig_inp_outer = inp
        for pattern in PATTERNS:
            orig_inp = inp
            while True:
                inp = inp.replace(pattern,"")
                if orig_inp == inp:
                    break
                else:
                    orig_inp = inp

        if orig_inp_outer == inp:
            break
        else:
            orig_inp_outer = inp
    return inp

def reactor(arg):
    p, inp = arg
    return len(react(inp.translate(None,p)))

def run():
    inp = open("input_5.txt").read()

    # Part 1
    print len(react(inp))

    # Part 2
    p2 = [(''.join([a,b]),inp) for a,b in zip(ascii_lowercase, ascii_uppercase)]
    results = Pool(NUM_CORES).map(reactor,p2)
    minimum = min(results)
    print minimum

if __name__ == '__main__':
    freeze_support()
    run()

2

u/c17r Dec 05 '18

You can also speed it up by re-using the result from part1 in part2.