-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday05.py
More file actions
255 lines (202 loc) · 6.63 KB
/
day05.py
File metadata and controls
255 lines (202 loc) · 6.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
from dataclasses import dataclass
import cupy as cp
import numpy as np
import nvtx
from cuda.compute import (
DoubleBuffer,
OpKind,
SortOrder,
TransformIterator,
ZipIterator,
inclusive_scan,
radix_sort,
reduce_into,
)
from numpy.typing import NDArray
@dataclass
class InputData:
lo: NDArray
hi: NDArray
val: NDArray
@nvtx.annotate("Input Parsing")
def read_input() -> InputData:
"""
Input structure (two blocks separated by a blank line):
RANGES BLOCK VALUES BLOCK
------------ ------------
3-5 1
10-14 5
16-20 8
12-18 11
17
32
Parsing turns the left block into pairs (L, R), and we sort L and R
separately on the GPU.
Original ranges:
3-5, 10-14, 16-20, 12-18
After sorting:
lo (range starts): [ 3, 10, 12, 16 ]
hi (range ends): [ 5, 14, 18, 20 ]
val (candidate IDs): [ 1, 5, 8, 11, 17, 32 ]
"""
with open("inputs/day05.in") as f:
all_data = f.read()
r_block, v_block = [x.strip() for x in all_data.split("\n\n", maxsplit=1)]
normalized = r_block.replace("\n", "-")
data = np.fromstring(normalized, sep="-", dtype=np.int64).reshape(-1, 2)
lo = cp.asarray(data[:, 0])
hi = cp.asarray(data[:, 1])
val = cp.fromstring(v_block, sep="\n", dtype=np.int64)
b_lo = DoubleBuffer(lo, cp.empty_like(lo))
b_hi = DoubleBuffer(hi, cp.empty_like(hi))
b_val = DoubleBuffer(val, cp.empty_like(val))
radix_sort(b_lo, None, None, None, SortOrder.ASCENDING, lo.size)
radix_sort(b_hi, None, None, None, SortOrder.ASCENDING, hi.size)
radix_sort(b_val, None, None, None, SortOrder.ASCENDING, val.size)
return InputData(b_lo.current(), b_hi.current(), b_val.current())
@nvtx.annotate("Part 1")
def part1(data: InputData) -> int:
"""
Goal
----
Count how many IDs in `val` fall inside at least one range [lo, hi].
Background trick
----------------
If arrays `lo` and `hi` are sorted:
starts(v) = number of ranges whose L ≤ v
ends(v) = number of ranges whose R < v
active(v) = starts(v) - ends(v)
An ID v is fresh if active(v) > 0.
Example
-------
Ranges:
[3,5], [10,14], [16,20], [12,18]
Values:
1 5 8 11 17 32
Sorted arrays:
lo: [ 3, 10, 12, 16 ]
hi: [ 5, 14, 18, 20 ]
val: [ 1, 5, 8, 11, 17, 32 ]
We compute:
first = searchsorted(lo, val, side="right")
(how many lo ≤ v)
last = searchsorted(hi, val, side="left")
(how many hi < v)
Pretty picture:
v: 1 5 8 11 17 32
--------------------------------------
first: 0 1 1 2 4 4
last: 0 0 1 1 1 4
--------------------------------------
diff: 0 1 0 1 3 0
--------------------------------------
valid: 0 1 0 1 1 0
Fresh mask = (diff > 0):
[0, 1, 0, 1, 1, 0] → total = 3
"""
out = cp.empty(1, dtype=cp.int32)
init = np.array([0], dtype=np.int32)
first = cp.searchsorted(data.lo, data.val, side="right")
last = cp.searchsorted(data.hi, data.val, side="left")
def valid(pair):
return int((pair[0] - pair[1]) > 0)
reduce_into(
TransformIterator(ZipIterator(first, last), valid),
out,
OpKind.PLUS,
first.size,
init,
)
return int(out[0].item())
@nvtx.annotate("Part 2")
def part2(data: InputData) -> int:
"""
Goal
----
Compute the total size of the union of all ranges (how many distinct
IDs are inside any range).
Sweep-line method
-----------------
Convert inclusive [L, R] ranges into half-open [L, R+1):
[L, R] → [L, R+1)
Emit “events”:
+1 at L
-1 at R+1
After sorting all event positions, an inclusive scan of deltas gives the
number of active intervals over each segment.
Example
-------
Original ranges:
[3,5], [10,14], [16,20], [12,18]
Half-open:
[3,6), [10,15), [16,21), [12,19)
Events (pos → delta):
3 : +1
6 : -1
10 : +1
15 : -1
16 : +1
21 : -1
12 : +1
19 : -1
Sorted:
pos: 3 6 10 12 15 16 19 21
delta: +1 -1 +1 +1 -1 +1 -1 -1
active: 1 0 1 2 1 2 1 0
↑ ↑ ↑ ↑ ↑ ↑ ↑ ↑
number of simultaneously-active intervals
Each segment spans consecutive positions:
segment width active contribution
------------------------------------------
[3,6) 3 1 3
[6,10) 4 0 0
[10,12) 2 1 2
[12,15) 3 2 6
[15,16) 1 1 1
[16,19) 3 2 6
[19,21) 2 1 2
-------------
total = 14
The GPU code constructs:
- positions p = [L..., R+1...]
- deltas d = [+1..., -1...]
- radix_sort(p, d)
- active = inclusive_scan(d)
- sum(active[i] * (pos[i+1] - pos[i]))
"""
lo = data.lo
hi = data.hi
n = lo.size
p = cp.empty(2 * n, dtype=lo.dtype)
d = cp.empty_like(p)
active = cp.empty_like(p)
out = cp.empty(1, dtype=cp.int64)
h_init = np.array([0], dtype=np.int64)
h_zero = np.array([0], dtype=np.int64)
p[:n] = lo
d[:n] = 1
p[n:] = hi + 1
d[n:] = -1
bpos = DoubleBuffer(p, cp.empty_like(p))
bdelta = DoubleBuffer(d, cp.empty_like(d))
radix_sort(bpos, None, bdelta, None, SortOrder.ASCENDING, p.size)
inclusive_scan(bdelta.current(), active, OpKind.PLUS, h_init, d.size)
cpos = bpos.current()
def compute(tup):
return (tup[0] - tup[1]) * (tup[2] > 0)
reduce_into(
TransformIterator(ZipIterator(cpos[1:], cpos[:-1], active[:-1]), compute),
out,
OpKind.PLUS,
2 * n - 1,
h_zero,
)
return int(out[0].item())
@nvtx.annotate("Day 05")
def main() -> tuple[int, int]:
data = read_input()
res1 = part1(data)
res2 = part2(data)
return res1, res2
if __name__ == "__main__":
print(*main())