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.

day03.nim 1.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. import intsets, sequtils, strscans, strutils
  2. var
  3. claims: seq[tuple[id, x, y, width, height: int]]
  4. max_x, max_y = int.low
  5. min_x, min_y = int.high
  6. for line in readFile("data/03.txt").strip.splitlines:
  7. var id, x, y, width, height: int
  8. if not line.scanf("#$i @ $i,$i: $ix$i", id, x, y, width, height):
  9. raise newException(Defect, "Invalid input line: " & line)
  10. claims.add((id, x, y, width, height))
  11. min_x = min(min_x, x)
  12. max_x = max(max_x, x + width)
  13. min_y = min(min_y, y)
  14. max_y = max(max_y, y + height)
  15. let
  16. x_range = 1 + max_x - min_x
  17. y_range = 1 + max_y - min_y
  18. var
  19. cells = newSeq[int](x_range * y_range)
  20. ids = initIntSet()
  21. overlaps = 0
  22. for claim in claims:
  23. var collision = false
  24. for x in claim.x..claim.x + claim.width - 1:
  25. for y in claim.y..claim.y + claim.height - 1:
  26. var
  27. index = (y - min_y) * y_range + (x - min_x)
  28. previous = cells[index]
  29. if previous == 0:
  30. cells[index] = claim.id
  31. elif previous == -1:
  32. collision = true
  33. else:
  34. collision = true
  35. overlaps.inc
  36. if previous in ids:
  37. ids.excl(previous)
  38. cells[index] = -1
  39. if not collision:
  40. ids.incl(claim.id)
  41. echo overlaps
  42. echo toSeq(ids.items)[0]