-
Notifications
You must be signed in to change notification settings - Fork 0
/
03.sql
64 lines (59 loc) · 1.58 KB
/
03.sql
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
-- load the input
DROP TABLE IF EXISTS input;
CREATE TABLE IF NOT EXISTS input (
inputline TEXT,
y SERIAL
);
COPY input (
inputline
)
FROM '/Users/ludwig/Library/CloudStorage/OneDrive-Persönlich/Dokumente/Projekte/adventofcode/03.txt';
WITH
coords as (
SELECT
generate_series as x,
i.y as y,
(string_to_array(i.inputline, NULL))[generate_series] as symbol
FROM
input i,
generate_series(1,140)
),
-- extract all the symbol locations from the input and store them in a separate table
symbols as (
SELECT *
from coords
WHERE symbol NOT IN ('1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.')
),
-- extract all the numbers and their bounding boxes and store them in a separate table
numbers as (
SELECT
UNNEST(regexp_matches(inputline, '[0-9]+', 'g')) as n,
y,
inputline,
generate_series()
FROM
input i
),
numbers2 as (
SELECT
cast((regexp_match(n, '[0-9]+$'))[1] as integer) as n,
y,
length(n) - length((regexp_match(n, '[0-9]+$'))[1]) -1 as xmin,
length(n) +1 as xmax,
inputline
FROM
numbers
),
part_numbers as (
SELECT
*
FROM
numbers2 n
INNER JOIN
symbols s
ON
n.xmin <= s.x AND s.x <= n.xmax
AND n.y -1 <= s.y AND s.y <= n.y +1
)
SELECT n, y FROM numbers;
-- join the two