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.

day19.nim 2.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import math, sequtils, strutils, tables
  2. type instr = tuple[op: string, a,b,c: int]
  3. let ops = {
  4. "addi": proc(regs: seq[int], a,b: int): int = regs[a] + b,
  5. "addr": proc(regs: seq[int], a,b: int): int = regs[a] + regs[b],
  6. "muli": proc(regs: seq[int], a,b: int): int = regs[a] * b,
  7. "mulr": proc(regs: seq[int], a,b: int): int = regs[a] * regs[b],
  8. "bani": proc(regs: seq[int], a,b: int): int = regs[a] and b,
  9. "banr": proc(regs: seq[int], a,b: int): int = regs[a] and regs[b],
  10. "bori": proc(regs: seq[int], a,b: int): int = regs[a] or b,
  11. "borr": proc(regs: seq[int], a,b: int): int = regs[a] or regs[b],
  12. "seti": proc(regs: seq[int], a,b: int): int = a,
  13. "setr": proc(regs: seq[int], a,b: int): int = regs[a],
  14. "gtir": proc(regs: seq[int], a,b: int): int = cast[int](a > regs[b]),
  15. "gtri": proc(regs: seq[int], a,b: int): int = cast[int](regs[a] > b),
  16. "gtrr": proc(regs: seq[int], a,b: int): int = cast[int](regs[a] > regs[b]),
  17. "eqir": proc(regs: seq[int], a,b: int): int = cast[int](a == regs[b]),
  18. "eqri": proc(regs: seq[int], a,b: int): int = cast[int](regs[a] == b),
  19. "eqrr": proc(regs: seq[int], a,b: int): int = cast[int](regs[a] == regs[b]),
  20. }.toTable
  21. var
  22. instructions: seq[instr]
  23. ip: int
  24. for line in readFile("data/19.txt").strip.splitlines:
  25. var parts = line.split(' ')
  26. if parts[0] == "#ip":
  27. ip = parts[1].parseInt
  28. else:
  29. instructions.add((parts[0], parts[1].parseInt, parts[2].parseInt, parts[3].parseInt))
  30. proc findTarget(part2: bool): int =
  31. # The instructions calculate the sum of all factors of a target number. The
  32. # target is initialised first, and then execution jumps back to near the
  33. # start of the program to perform the calculation. To find the target
  34. # number, we evaluate until a backwards jump and then just take the largest
  35. # register. (Yuck.)
  36. var registers = @[if part2: 1 else: 0, 0, 0, 0, 0, 0]
  37. while true:
  38. let
  39. i = registers[ip]
  40. instr = instructions[i]
  41. registers[instr.c] = ops[instr.op](registers, instr.a, instr.b)
  42. registers[ip].inc
  43. if registers[ip] < i:
  44. return registers.max
  45. proc factors(n: int): seq[int] =
  46. for x in 1 .. int(sqrt(float(n))):
  47. if n mod x == 0:
  48. result.add(x)
  49. result.add(n div x)
  50. echo findTarget(false).factors.sum
  51. echo findTarget(true).factors.sum