My solutions to 2018's advent of code
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.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.

elfcode.nim 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. import strutils, tables
  2. type
  3. instr* = tuple[op: string, a,b,c: int]
  4. instructionSet* = tuple[ipr: int, instructions: seq[instr]]
  5. let ops* = {
  6. "addi": proc(regs: seq[int], a,b: int): int = regs[a] + b,
  7. "addr": proc(regs: seq[int], a,b: int): int = regs[a] + regs[b],
  8. "muli": proc(regs: seq[int], a,b: int): int = regs[a] * b,
  9. "mulr": proc(regs: seq[int], a,b: int): int = regs[a] * regs[b],
  10. "bani": proc(regs: seq[int], a,b: int): int = regs[a] and b,
  11. "banr": proc(regs: seq[int], a,b: int): int = regs[a] and regs[b],
  12. "bori": proc(regs: seq[int], a,b: int): int = regs[a] or b,
  13. "borr": proc(regs: seq[int], a,b: int): int = regs[a] or regs[b],
  14. "seti": proc(regs: seq[int], a,b: int): int = a,
  15. "setr": proc(regs: seq[int], a,b: int): int = regs[a],
  16. "gtir": proc(regs: seq[int], a,b: int): int = cast[int](a > regs[b]),
  17. "gtri": proc(regs: seq[int], a,b: int): int = cast[int](regs[a] > b),
  18. "gtrr": proc(regs: seq[int], a,b: int): int = cast[int](regs[a] > regs[b]),
  19. "eqir": proc(regs: seq[int], a,b: int): int = cast[int](a == regs[b]),
  20. "eqri": proc(regs: seq[int], a,b: int): int = cast[int](regs[a] == b),
  21. "eqrr": proc(regs: seq[int], a,b: int): int = cast[int](regs[a] == regs[b]),
  22. }.toTable
  23. proc readInstructions*(input: seq[string]): instructionSet =
  24. for line in input:
  25. var parts = line.split(' ')
  26. if parts[0] == "#ip":
  27. result.ipr = parts[1].parseInt
  28. else:
  29. result.instructions.add((parts[0], parts[1].parseInt, parts[2].parseInt, parts[3].parseInt))
  30. proc ip*(instructionSet: instructionSet, registers: seq[int]): int {.inline.} =
  31. registers[instructionSet.ipr]
  32. proc currentInstr*(instructionSet: instructionSet, registers: seq[int]): instr {.inline.} =
  33. instructionSet.instructions[instructionSet.ip(registers)]
  34. proc step*(instructionSet: instructionSet, registers: var seq[int]) {.inline.} =
  35. let instr = instructionSet.currentInstr(registers)
  36. registers[instr.c] = ops[instr.op](registers, instr.a, instr.b)
  37. registers[instructionSet.ipr].inc