Skip to content

Instantly share code, notes, and snippets.

@valsteen
Created December 23, 2015 15:58
Show Gist options
  • Save valsteen/71d690a84736e591b02d to your computer and use it in GitHub Desktop.
Save valsteen/71d690a84736e591b02d to your computer and use it in GitHub Desktop.
Python solution for Advent of Code day 23 http://adventofcode.com/day/23
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import re
from collections import defaultdict
from functools import partial
i = """jio a, +18
inc a
tpl a
inc a
tpl a
tpl a
tpl a
inc a
tpl a
inc a
tpl a
inc a
inc a
tpl a
tpl a
tpl a
inc a
jmp +22
tpl a
inc a
tpl a
inc a
inc a
tpl a
inc a
tpl a
inc a
inc a
tpl a
tpl a
inc a
inc a
tpl a
inc a
inc a
tpl a
inc a
inc a
tpl a
jio a, +8
inc b
jie a, +4
tpl a
inc a
jmp +2
hlf a
jmp -7"""
registers = defaultdict(lambda: 0)
registers['a'] = 1 # comment for first part
instructions = []
execution_pointer = 0
def debug(*s):
# return -- uncomment for quiet output
print "%10s %-20s %s" % (execution_pointer, " ".join(str(c) for c in s), "\t".join("%s = %s" % (k,v) for k, v in registers.items()))
def hlf(register):
global execution_pointer
debug("hlf", register)
registers[register] /= 2
execution_pointer += 1
def tpl(register):
global execution_pointer
debug("tpl", register)
registers[register] *= 3
execution_pointer += 1
def inc(register):
global execution_pointer
debug("inc", register)
registers[register] += 1
execution_pointer += 1
def jmp(offset):
global execution_pointer
debug("jmp", offset)
execution_pointer += offset
def jie(register, offset):
global execution_pointer
debug("jie", register, offset)
if registers[register] % 2 == 0:
execution_pointer += offset
else:
execution_pointer += 1
def jio(register, offset):
global execution_pointer
debug("jio", register, offset)
if registers[register] == 1:
execution_pointer += offset
else:
execution_pointer += 1
for l in i.split("\n"):
parts = re.split("[ ,]+", l)
instruction = parts.pop(0)
if instruction == "hlf":
register = parts.pop(0)
instructions.append(partial(hlf, register))
elif instruction == "tpl":
register = parts.pop(0)
instructions.append(partial(tpl, register))
elif instruction == "inc":
register = parts.pop(0)
instructions.append(partial(inc, register))
elif instruction == "jmp":
offset = int(parts.pop(0))
instructions.append(partial(jmp, offset))
elif instruction == "jie":
register = parts.pop(0)
offset = int(parts.pop(0))
instructions.append(partial(jie, register, offset))
elif instruction == "jio":
register = parts.pop(0)
offset = int(parts.pop(0))
instructions.append(partial(jio, register, offset))
else:
raise Exception(l)
try:
while True:
instructions[execution_pointer]()
except IndexError:
pass
print "\n".join("%s = %s" % (k,v) for k,v in registers.items())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment