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

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