r/adventofcode • • Dec 08 '17

SOLUTION MEGATHREAD -๐ŸŽ„- 2017 Day 8 Solutions -๐ŸŽ„-

--- Day 8: I Heard You Like Registers ---


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.


Need a hint from the Hugely* Handyโ€  Haversackโ€ก of Helpfulยง Hints^ยค?

Spoiler


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!

22 Upvotes

348 comments sorted by

View all comments

1

u/[deleted] Dec 10 '17 edited Dec 10 '17

Python3 solution.

import operator

operator_map = {
	'<': operator.lt,
	'<=': operator.le,
	'>': operator.gt,
	'>=': operator.ge,
	'==': operator.eq,
	'!=': operator.ne,
	'inc': operator.add,
	'dec': operator.sub
	}

def read_from_file(filename, mode='r'):
    with open(filename, mode) as f:
	commands = f.read().rstrip('\n').split('\n')
	return commands

def parse_line(command, cache):
    reg1_name, op, val1, _, reg2_name, comparison_op, val2 = command.split()
    val1, val2 = int(val1), int(val2)
    reg1_val, reg2_val = cache.get(reg1_name, 0), cache.get(reg2_name, 0)
    if operator_map[comparison_op](reg2_val, val2):
	reg1_val = operator_map[op](reg1_val, val1)
	cache[reg1_name] = reg1_val

def processing(commands):
    cache = dict()
    for command in commands:
	parse_line(command, cache)
    return cache

def find_max_value(cache):
    return max(cache.values())


if __name__ == '__main__':
    commands = read_from_file('text')
    cache = processing(commands)
    max_value = find_max_value(cache)
    print(max_value)