You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

vm.go 872B

1234567891011121314151617181920212223242526272829303132333435363738
  1. package intcode
  2. // VirtualMachine is an IntCode virtual machine.
  3. type VirtualMachine struct {
  4. ip int
  5. opcodes map[int]OpcodeFunc
  6. Memory []int
  7. Halted bool
  8. }
  9. // NewVirtualMachine creates a new IntCode virtual machine, initialised
  10. // to the given slice of memory.
  11. func NewVirtualMachine(memory []int) *VirtualMachine {
  12. return &VirtualMachine{
  13. ip: 0,
  14. Memory: memory,
  15. Halted: false,
  16. opcodes: map[int]OpcodeFunc{
  17. 1: AddOpcode,
  18. 2: MulOpcode,
  19. 99: HaltOpcode,
  20. },
  21. }
  22. }
  23. // Run repeatedly executes instructions until the VM halts.
  24. func (vm *VirtualMachine) Run() {
  25. for !vm.Halted {
  26. vm.opcodes[vm.Memory[vm.ip]](vm, vm.Memory[vm.ip+1:])
  27. }
  28. }
  29. // Reset resets the memory to the given slice, and all other state back to its original value.
  30. func (vm *VirtualMachine) Reset(memory []int) {
  31. copy(vm.Memory, memory)
  32. vm.ip = 0
  33. vm.Halted = false
  34. }