-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path11_02.sql
113 lines (97 loc) · 2.52 KB
/
11_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
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
create table T (row text) strict;
.import 11_input.txt T
.load ./regex0.so
.mode box
-- parse input
with
-- P contains the problem input
P(v) as materialized (
select
cast(R.match as integer)
from regex_find_all('\d+', T.row) as R
join T
),
S(i, v) as (
select 0, v from P
-- case: v = 0
union
select i+1, 1 from S
where v = 0 and i < 75
-- case: even length
union
select i+1, cast(substr(v, 0,length(v)/2+1) as integer) from S
where length(v) % 2 = 0 and i < 75
union
select i+1, cast(substr(v, length(v)/2+1) as integer) from S
where length(v) % 2 = 0 and i < 75
-- case: otherwise
union
select i+1, v*2024 from S
where v != 0 and length(v) % 2 != 0 and i < 75
),
-- here we need to simulate a for-loop
-- since SQLite doesn't support aggregate recursive queries
-- nor recursive queries that do multiple self-references
-- in a single select
Q(n, i, v) as (
select row_number() over (order by i asc), S.i, S.v from S
),
K(n, j) as (
-- base case
select 0, jsonb_array(jsonb_group_object(S.v, 1))
from S
where S.i = 0
-- case: v = 0
union all
select
K.n+1,
jsonb_set(
K.j,
printf('$[%d].%d', Q.i+1, 1),
coalesce(K.j -> printf('$[%d].%d', Q.i+1, 1), 0)
+ (K.j -> printf('$[%d].%d', Q.i, 0))
)
from K join Q on K.n+1 = Q.n
where v = 0
-- case: even length
union all
select
K.n+1,
jsonb_set(
jsonb_set(
K.j,
printf('$[%d].%d', Q.i+1, substr(v, length(v)/2+1)),
coalesce(K.j -> printf('$[%d].%d', Q.i+1, substr(v, length(v)/2+1)), 0)
+ (K.j -> printf('$[%d].%d', Q.i, v))
),
printf('$[%d].%d', Q.i+1, substr(v, 0,length(v)/2+1)),
coalesce(K.j -> printf('$[%d].%d', Q.i+1, substr(v, 0,length(v)/2+1)), 0)
+ (K.j -> printf('$[%d].%d', Q.i, v) * (case when substr(v, 0,length(v)/2+1) = substr(v, length(v)/2+1) then 2 else 1 end))
)
from K join Q on K.n+1 = Q.n
where v != 0 and length(v) % 2 = 0
-- case: otherwise
union all
select
K.n+1,
-- we set the old key to null here since otherwise
-- we get a quadratic algorithm due to copying
jsonb_set(
jsonb_set(
K.j,
printf('$[%d].%d', Q.i+1, v*2024),
coalesce(K.j -> printf('$[%d].%d', Q.i+1, v*2024), 0)
+ (K.j -> printf('$[%d].%d', Q.i, v))
),
printf('$[%d]', case when Q.i-2 >= 0 then Q.i-2 else 1000 end),
NULL
)
from K join Q on K.n+1 = Q.n
where v != 0 and length(v) % 2 != 0
),
R as (
select * from K order by n desc limit 1
)
select K.value, sum(json_each.value) from R join json_each(R.j ->> printf('$[%d]',K.value))
join generate_series(0, 75) as K
group by K.value;