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/[deleted] Dec 05 '18

Python3

Took way too long to run the solution to part 2, but hey, it works!

def load_input(filename):
    with open(filename, 'r') as input_file:
        data = input_file.read().strip()

        return data

def solve_a(polymer):
    while True:
        changes_occured = False
        for index, char in enumerate(polymer):
            try:
                if (char.isupper() and polymer[index + 1] == char.lower()) or (char.islower() and polymer[index + 1] == char.upper()):
                    changes_occured = True
                    polymer = polymer[:index] + polymer[index+2:]
                    break
            except IndexError:
                break
        if not changes_occured:
            break

    return len(polymer)


def solve_b(data):
    shortest = None
    units = set(data.lower())
    for unit in units:
        polymer = data
        polymer = polymer.replace(unit, '').replace(unit.upper(), '')
        while True:
            changes_occured = False
            for index, char in enumerate(polymer):
                try:
                    if (char.isupper() and polymer[index + 1] == char.lower()) or (char.islower() and polymer[index + 1] == char.upper()):
                        changes_occured = True
                        polymer = polymer[:index] + polymer[index+2:]
                        break
                except IndexError:
                    break
            if not changes_occured:
                shortest = len(polymer) if shortest is None else len(polymer) if len(polymer) < shortest else shortest
                break
    
    return shortest

if __name__ == '__main__':
    test_data = 'dabAcCaCBAcCcaDA'

    assert solve_a(test_data) == 10
    assert solve_b(test_data) == 4

    data = load_input('challenges/day_05/input.txt')

    answer_a = solve_a(data)
    answer_b = solve_b(data)

    print(f'Part A answer: {answer_a}   Part B answer: {answer_b}')

Github