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 993B

12345678910111213141516171819202122232425
  1. import elfcode, math, sequtils, strutils, tables
  2. var instructionSet = readInstructions(readFile("data/19.txt").strip.splitlines)
  3. proc findTarget(part2: bool = false): int =
  4. # The instructions calculate the sum of all factors of a target number. The
  5. # target is initialised first, and then execution jumps back to near the
  6. # start of the program to perform the calculation. To find the target
  7. # number, we evaluate until a backwards jump and then just take the largest
  8. # register. (Yuck.)
  9. var registers = @[if part2: 1 else: 0, 0, 0, 0, 0, 0]
  10. while true:
  11. let i = instructionSet.ip(registers)
  12. instructionSet.step(registers)
  13. if instructionSet.ip(registers) < i:
  14. return registers.max
  15. proc factors(n: int): seq[int] =
  16. for x in 1 .. int(sqrt(float(n))):
  17. if n mod x == 0:
  18. result.add(x)
  19. result.add(n div x)
  20. echo findTarget().factors.sum
  21. echo findTarget(true).factors.sum