advent/2016/10-1.py

72 lines
1.5 KiB
Python
Raw Normal View History

2017-01-17 00:39:03 +00:00
# Python!
import collections
2017-01-18 23:16:47 +00:00
class robot:
2017-01-17 00:39:03 +00:00
def __init__(self, instructions):
words = instructions.split()
self.number = words[1]
self.chips = []
self.recipients = {
'low': words[5:7],
'high': words[10:]
}
def give(self, value, recipient):
recip_type, recip_num = recipient
if recip_type == 'output':
outputs[recip_num].append(value)
else:
bots[recip_num].take(value)
def take(self, value):
self.chips.append(value)
if len(self.chips) > 1:
2017-01-18 23:16:47 +00:00
xqueue.append(self)
2017-01-17 00:39:03 +00:00
def execute(self):
2017-01-18 23:16:47 +00:00
if len(self.chips) > 2:
print('Error, bot', self.number, 'has chips', self.chips)
elif len(self.chips) == 2:
low, high = min(self.chips), max(self.chips)
2017-01-17 00:39:03 +00:00
2017-01-18 23:16:47 +00:00
if low == 17 and high == 61:
print('responsible bot is bot', self.number)
print('17 goes to', self.recipients['low'])
print('61 goes to', self.recipients['high'])
2017-01-17 00:39:03 +00:00
2017-01-18 23:16:47 +00:00
del self.chips[:]
self.give(low, self.recipients['low'])
self.give(high, self.recipients['high'])
2017-01-17 00:39:03 +00:00
with open('10.txt') as file:
instructions = file.read().splitlines()
get_instructions = []
bot_definitions = []
2017-01-18 23:16:47 +00:00
xqueue = []
2017-01-17 00:39:03 +00:00
bots = {}
2017-01-18 23:16:47 +00:00
outputs = collections.defaultdict(list)
2017-01-17 00:39:03 +00:00
for inst in instructions:
if inst[0] == 'v':
get_instructions.append(inst)
else:
bot_definitions.append(inst)
for definition in bot_definitions:
2017-01-18 23:16:47 +00:00
b = robot(definition)
2017-01-17 00:39:03 +00:00
bots[b.number] = b
for i in get_instructions:
2017-01-18 23:16:47 +00:00
words = i.split()
bot_num = words[5]
value = int(words[1])
bots[bot_num].chips.append(value)
bots['97'].execute()
while xqueue:
current_bot = xqueue.pop(0)
current_bot.execute()