-
Notifications
You must be signed in to change notification settings - Fork 0
/
02.sql
79 lines (74 loc) · 1.75 KB
/
02.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
-- parsing input
DROP TABLE IF EXISTS input;
CREATE TABLE IF NOT EXISTS input (
inputline TEXT
);
COPY input (
inputline
)
FROM 'path-to-02.txt'
;
WITH
gamenumber as (
SELECT
inputline,
regexp_matches(inputline, '(Game )([0-9]+)(: )(.*)', 'g') as parsed
FROM input
),
parsed as (
SELECT
inputline,
parsed[2] as game_id,
unnest(string_to_array(unnest(string_to_array(parsed[4], ';')), ',')) as games
FROM gamenumber
),
parsed2 as (
SELECT
game_id,
CAST ((string_to_array(TRIM(games), ' '))[1] as INTEGER) as number_of_cubes,
(string_to_array(TRIM(games), ' '))[2] as color
FROM parsed
),
forbidden_bags as (
SELECT
game_id
FROM
parsed2
WHERE
color='red' AND number_of_cubes > 12
OR color='green' AND number_of_cubes > 13
OR color='blue' AND number_of_cubes > 14
),
legal_bags as (
SELECT
DISTINCT p.game_id
FROM
parsed p
LEFT JOIN
forbidden_bags f
ON f.game_id = p.game_id
WHERE
f.game_id IS NULL
),
--- this is the solution to part 1
part1 as (
SELECT sum(cast(game_id as integer)) from legal_bags
),
minimum_cubes as (
SELECT
game_id,
color,
max(number_of_cubes) as min_number
FROM parsed2
GROUP BY game_id, color
),
with_power as (
SELECT
round(exp(sum(ln(min_number)))) as power,
game_id
FROM minimum_cubes
GROUP BY game_id
)
SELECT
sum("power")
FROM with_power