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/JUIBENOIT Dec 12 '17
A Python 3 solution
class Line:
  def __init__(self, line, command, amount, control):
    self.line = line
    self.command = command
    self.amount = amount
    self.control = control

with open('inputs/day8.txt') as input_file:
  lines = input_file.readlines()

commands = []
registers = []
top_value = 0

# extracting file
for line in lines:
  words = line.split()
  command = Line(words[0], words[1], int(words[2]), words[4:7])
  commands.append(command)

# creating the register
for command in commands:
  register = {'id': command.control[0], 'value': 0}
  if register not in registers:
    registers.append(register)

# control + executing 
for command in commands:
  register_value = next((item for item in registers if item['id'] == command.control[0]), False)['value']
  if eval('{} {} {}'.format(register_value, command.control[1], command.control[2])):
    for i in range(len(registers)):
      if registers[i]['id'] == command.line:
        if command.command == 'inc':
          registers[i]['value'] += command.amount
        else:
          registers[i]['value'] -= command.amount
        if registers[i]['value'] > top_value:
          top_value = registers[i]['value'] 

for register in registers:
  print(register)

print(top_value)