#!/usr/bin/env tclsh while {[gets stdin line] >= 0} { if {$line eq ""} continue lappend memory [split $line { }] } proc run {memory} { set pc 0 set acc 0 set n [llength $memory] while 1 { if {[info exists visited($pc)]} {return $acc} if {$pc >= $n} {puts $acc; exit} set visited($pc) 1 lassign [lindex $memory $pc] op arg switch -- $op { nop {incr pc} acc {incr acc $arg; incr pc} jmp {incr pc $arg} } } } puts [run $memory] for {set i 0} {$i < [llength $memory]} {incr i} { lassign [lindex $memory $i] op arg switch -- $op { nop { run [lreplace $memory $i $i [list jmp $arg]] } jmp { run [lreplace $memory $i $i [list nop $arg]] } } }