Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/local/bin/gst -q
- Array extend [
- atInc: idx [
- ^self at: idx put: ((self at: idx) + 1)
- ]
- ]
- Object subclass: VirtualMachine [
- | acc ip opcodes code toggle |
- VirtualMachine class >> new [
- ^(super new) init
- ]
- init [
- opcodes := Dictionary new.
- opcodes at: #acc put: [ :a | acc := acc + a. ip := ip + 1 ];
- at: #jmp put: [ :a | ip := ip + a ];
- at: #nop put: [ :a | ip := ip + 1 ].
- toggle := Dictionary new.
- toggle at: #nop put: #jmp;
- at: #jmp put: #nop;
- at: #acc put: #acc.
- code := OrderedCollection new.
- ^self
- ]
- load: op arg: arg [
- code addLast: (op -> arg)
- ]
- halted [
- ^(ip = (code size + 1))
- ]
- run [
- | inst ran |
- acc := 0.
- ip := 1.
- ran := Array new: (code size + 1) withAll: 0.
- [ self halted ] whileFalse: [
- ((ran atInc: ip) = 2) ifTrue: [ " looped "
- ^acc
- ].
- inst := code at: ip.
- (opcodes at: inst key) value: inst value.
- ].
- ^acc
- ]
- try: inst [
- (code at: inst) key: (toggle at: (code at: inst) key).
- self run.
- (code at: inst) key: (toggle at: (code at: inst) key).
- ^self halted.
- ]
- getAcc [ ^acc ]
- codeSize [ ^code size ]
- ]
- "
- | Mainline
- "
- vm := VirtualMachine new.
- stdin linesDo: [ :line |
- split := line subStrings: ' +'.
- vm load: (split first asSymbol) arg: (split second asNumber).
- ].
- stdout nextPutAll: ('Part 1: ', vm run asString); nl.
- " XXX: Check and don't bother with trying to toggle #acc "
- (1 to: (vm codeSize)) detect: [ :inst | vm try: inst ].
- stdout nextPutAll: ('Part 2: ', vm getAcc asString); nl.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement