-
Notifications
You must be signed in to change notification settings - Fork 0
/
05.walis_response_hilight.sql
91 lines (91 loc) · 1.77 KB
/
05.walis_response_hilight.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
WITH RECURSIVE
all_factors (initial, factor, final) AS
(
SELECT s, s, FALSE
FROM generate_series(2, 99 * 99) s
UNION ALL
SELECT initial, f, d IN (1, factor)
FROM (
SELECT initial, factor, d
FROM all_factors
CROSS JOIN
LATERAL
(
SELECT d
FROM generate_series(TRUNC(SQRT(factor))::INTEGER, 1, -1) d
WHERE factor % d = 0
LIMIT 1
) q (d)
WHERE NOT final
) q
CROSS JOIN
LATERAL
(
VALUES
(d),
(factor / d)
) p (f)
WHERE f NOT IN (initial, 1)
),
factors AS
(
SELECT initial, factor,
ROW_NUMBER() OVER (PARTITION BY initial ORDER BY factor) rn
FROM all_factors
WHERE final
),
powerset_factors AS
(
SELECT initial, factor, rn
FROM factors
UNION ALL
SELECT p.initial, p.factor * f.factor, f.rn
FROM powerset_factors p
JOIN factors f
ON f.initial = p.initial
AND f.rn > p.rn
),
pairs AS
(
SELECT initial,
(LEAST(one, two), GREATEST(one, two)) pair
FROM (
SELECT initial,
factor one,
initial / factor two
FROM powerset_factors
WHERE initial NOT IN (1, factor)
) q
WHERE one BETWEEN 2 AND 99
AND two BETWEEN 2 AND 99
),
alis_first AS
(
SELECT *
FROM (
SELECT initial, COUNT(DISTINCT pair) alis_first_ways
FROM pairs
GROUP BY
initial
) q
WHERE alis_first_ways >= 2
)
SELECT ' ' || STRING_AGG(CASE WHEN x % 10 = 0 THEN (x / 10)::TEXT ELSE ' ' END, '')
FROM generate_series(2, 99) x
UNION ALL
SELECT ' ' || STRING_AGG((x % 10)::TEXT, '')
FROM generate_series(2, 99) x
UNION ALL
(
SELECT LPAD(y::TEXT, 3, '0') || ' ' || LEFT(STRING_AGG(CASE WHEN alis_first_ways IS NOT NULL THEN CASE WHEN x + y IN (9, 11) THEN TO_HEX(x + y) ELSE '.' END ELSE ' ' END, '' ORDER BY x), 99)
FROM generate_series(2, 99) y
CROSS JOIN
generate_series(2, 99) x
LEFT JOIN
alis_first
ON initial = x * y
GROUP BY
y
ORDER BY
y
)