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