This repository was archived by the owner on May 13, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathpart1.sqlite.sql
102 lines (96 loc) · 3.02 KB
/
part1.sqlite.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
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
-- our puzzle input
CREATE TABLE input (value STRING);
INSERT INTO input VALUES (TRIM(readfile('input.txt'), char(10)));
CREATE TABLE parents (parent TEXT, n INT, child TEXT);
WITH RECURSIVE
nn (parent, n, child, rest)
AS (
SELECT
'',
0,
'',
(SELECT value FROM input)
UNION ALL
SELECT
CASE (
(
INSTR(nn.rest, ',') = 0 OR
INSTR(nn.rest, ' contain ') < INSTR(nn.rest, ',')
) AND (
INSTR(nn.rest, '.') = 0 OR
INSTR(nn.rest, ' contain ') < INSTR(nn.rest, '.')
)
)
WHEN 1 THEN SUBSTR(nn.rest, 0, INSTR(nn.rest, ' bags'))
ELSE nn.parent
END,
CASE (
(
INSTR(nn.rest, ',') = 0 OR
INSTR(nn.rest, ' contain ') < INSTR(nn.rest, ',')
) AND (
INSTR(nn.rest, '.') = 0 OR
INSTR(nn.rest, ' contain ') < INSTR(nn.rest, '.')
)
)
WHEN 1 THEN
CASE SUBSTR(nn.rest, INSTR(nn.rest, ' contain ') + 9) LIKE 'no other%'
WHEN 1 THEN 0
ELSE SUBSTR(nn.rest, INSTR(nn.rest, ' contain ') + 9, 1)
END
ELSE SUBSTR(nn.rest, 1, 1)
END,
CASE (
(
INSTR(nn.rest, ',') = 0 OR
INSTR(nn.rest, ' contain ') < INSTR(nn.rest, ',')
) AND (
INSTR(nn.rest, '.') = 0 OR
INSTR(nn.rest, ' contain ') < INSTR(nn.rest, '.')
)
)
WHEN 1 THEN
CASE SUBSTR(nn.rest, INSTR(nn.rest, ' contain ') + 9) LIKE 'no other%'
WHEN 1 THEN ''
ELSE SUBSTR(
nn.rest,
INSTR(nn.rest, ' contain ') + 11,
-1 + INSTR(
SUBSTR(
nn.rest,
INSTR(nn.rest, ' contain ') + 11
),
' bag'
)
)
END
ELSE SUBSTR(nn.rest, 3, INSTR(nn.rest, ' bag') - 3)
END,
CASE (
INSTR(nn.rest, ',') > 0 AND
INSTR(nn.rest, ',') < INSTR(nn.rest, '.')
)
WHEN 1 THEN SUBSTR(nn.rest, INSTR(nn.rest, ',') + 2)
ELSE SUBSTR(nn.rest, INSTR(nn.rest, '.') + 2)
END
FROM nn
WHERE LENGTH(nn.rest) > 0
)
INSERT INTO parents (parent, n, child)
SELECT nn.parent, nn.n, nn.child
FROM nn WHERE nn.parent != '' AND nn.child != '';
CREATE TABLE colors (color);
CREATE TABLE stack (color);
PRAGMA recursive_triggers = on;
CREATE TEMP TRIGGER ttrig
AFTER INSERT ON stack
BEGIN
INSERT INTO colors
SELECT parent FROM parents
WHERE child = NEW.color;
INSERT INTO stack
SELECT parent FROM parents
WHERE child = NEW.color;
END;
INSERT INTO stack VALUES ('shiny gold');
SELECT COUNT(DISTINCT color) FROM colors;