85 lines
2.3 KiB
Python
Executable File
85 lines
2.3 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 = []
|
|
|
|
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 False
|
|
|
|
BOTS[number]['values'] = sorted(BOTS[number]['values'])
|
|
BOTS_MOVES.append(number)
|
|
|
|
if BOTS[number]['values'][0] == 17:
|
|
if BOTS[number]['values'][1] == 61:
|
|
print(number)
|
|
return True
|
|
return False
|
|
|
|
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])
|
|
if check_robot(BOT['low_number']):
|
|
break
|
|
if BOTS[bot]['high'] == 'bot':
|
|
BOTS[BOT['high_number']]['values'].append(BOT['values'][1])
|
|
if check_robot(BOT['high_number']):
|
|
break
|
|
BOT['values'] = []
|
|
|
|
|
|
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)
|