adventofcode-2016/10/part02.py
Peter Hudec 5998d17b6a
day 10
2018-01-21 23:41:50 +01:00

85 lines
2.5 KiB
Python
Executable File

#!/usr/bin/env python
import re
import argparse
RE_BOT = re.compile(r'^bot (\d+) gives low to (.*) (\d+) and high to (.*) (\d+)$')
RE_VALUE = re.compile(r'value (\d+) goes to bot (\d+)$')
BOTS = dict()
BOTS_MOVES = []
OUTPUTS = dict()
def load_file(filename):
with open(filename) as f:
for line in f:
yield line.strip()
def check_robot(number):
if len(BOTS[number]['values']) != 2:
return
BOTS[number]['values'] = sorted(BOTS[number]['values'])
BOTS_MOVES.append(number)
def process_input(line):
match = RE_BOT.search(line)
if match:
bot = int(match.group(1))
if bot not in BOTS:
BOTS[bot] = {
'values': [],
'low': None,
'high': None
}
BOTS[bot]['low'] = match.group(2)
BOTS[bot]['low_number'] = int(match.group(3))
BOTS[bot]['high'] = match.group(4)
BOTS[bot]['high_number'] = int(match.group(5))
return
match = RE_VALUE.search(line)
if match:
bot = int(match.group(2))
if bot not in BOTS:
BOTS[bot] = {
'values': [],
'low': None,
'high': None
}
BOTS[bot]['values'].append(int(match.group(1)))
check_robot(bot)
return
raise Exception("could not parse line: {}".format(line))
def main(args):
for LINE in load_file(args.input):
process_input(LINE)
while len(BOTS_MOVES):
bot = BOTS_MOVES.pop(0)
BOT = BOTS[bot]
if BOT['low'] == 'bot':
BOTS[BOT['low_number']]['values'].append(BOT['values'][0])
check_robot(BOT['low_number'])
if BOTS[bot]['high'] == 'bot':
BOTS[BOT['high_number']]['values'].append(BOT['values'][1])
check_robot(BOT['high_number'])
if BOT['low'] == 'output':
if BOT['low_number'] not in OUTPUTS:
OUTPUTS[BOT['low_number']] = []
OUTPUTS[BOT['low_number']].append(BOT['values'][0])
if BOT['high'] == 'output':
if BOT['high_number'] not in OUTPUTS:
OUTPUTS[BOT['high_number']] = []
OUTPUTS[BOT['high_number']].append(BOT['values'][1])
print(OUTPUTS[0][0]*OUTPUTS[1][0]*OUTPUTS[2][0])
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='AdventOfCode 2016 Day 01')
parser.add_argument('--input', '-i', action='store', required=True, help='input file')
args = parser.parse_args()
main(args)