Skip to content

Instantly share code, notes, and snippets.

@fxn
Created Dec 8, 2020
Embed
What would you like to do?
import intsets, strutils, strscans, sequtils
type
Opcode = enum
acc = "acc"
jmp = "jmp"
nop = "nop"
Instruction = tuple
opcode: Opcode
arg: int
RunStatus = enum
InfiniteLoop, Finished
proc parseInstruction(line: string): Instruction =
var
opcode: string
arg: int
if scanf(line, "$w $i", opcode, arg):
result = (parseEnum[Opcode](opcode), arg)
func run(instructions: seq[Instruction]): (RunStatus, int) =
var
ip = 0
totalAcc = 0
visited: IntSet
while true:
if visited.contains(ip):
return (InfiniteLoop, totalAcc)
elif ip >= instructions.len:
return (Finished, totalAcc)
visited.incl(ip)
case instructions[ip].opcode:
of acc:
totalAcc += instructions[ip].arg
ip += 1
of jmp:
ip += instructions[ip].arg
of nop:
ip += 1
var lastMutation = -1
var originalInstructions = toSeq(stdin.lines).map(parseInstruction)
while true:
var instructions = originalInstructions
for i in lastMutation + 1 .. instructions.high:
if instructions[i].opcode == nop:
instructions[i].opcode = jmp
lastMutation = i
break
elif instructions[i].opcode == jmp:
instructions[i].opcode = nop
lastMutation = i
break
let (status, totalAcc) = run(instructions)
if status == Finished:
echo totalAcc
break
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment