My solutions to 2018's advent of code
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
Ce dépôt est archivé. Vous pouvez voir les fichiers et le cloner, mais vous ne pouvez pas pousser ni ouvrir de ticket/demande d'ajout.

day11.nim 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import math, sequtils, strscans, strutils
  2. func power(serial, x, y: int): int =
  3. let rackId = x + 10
  4. (rackId * y + serial) * rackId div 100 mod 10 - 5
  5. var
  6. serial = readFile("data/11.txt").strip.parseInt
  7. prefixSum: array[-1..300, array[-1..300, int]]
  8. for x in 0..299:
  9. for y in 0..299:
  10. # Construct a prefix sum of the grid: prefixSum[x][y] holds the sum of
  11. # all cells in the rectangle from (0,0) to (x,y). We calculate this
  12. # by adding the current cell to the rectangle above and the rectangle
  13. # to the left. This results in double-counting the rect between (0,0)
  14. # and (x-1,y-1), so we subtract that from the result.
  15. prefixSum[x][y] = power(serial, x+1, y+1) + prefixSum[x][y-1] +
  16. prefixSum[x-1][y] - prefixSum[x-1][y-1]
  17. var
  18. best = int.low
  19. bestPos = ""
  20. bestThree = int.low
  21. bestThreePos = ""
  22. for size in 1..300:
  23. let s1 = size - 1
  24. for x in 0..300 - size:
  25. for y in 0..300 - size:
  26. # To use the prefix sum to find the value of a rect, we take the
  27. # value for the lower right corner and subtract the rects to the
  28. # left and the top. Like when constructing the prefix sum this
  29. # double-counts the rectangle diagonally to the top left, so we
  30. # re-add that.
  31. var sum = prefixSum[x+s1][y+s1] - prefixSum[x-1][y+s1] -
  32. prefixSum[x+s1][y-1] + prefixSum[x-1][y-1]
  33. if sum > best:
  34. best = sum
  35. bestPos = $(x + 1) & "," & $(y + 1) & "," & $size
  36. if size == 3 and sum > bestThree:
  37. bestThree = sum
  38. bestThreePos = $(x + 1) & "," & $(y + 1)
  39. echo bestThreePos
  40. echo bestPos