-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2020_day19.lua
More file actions
78 lines (72 loc) · 1.36 KB
/
Copy path2020_day19.lua
File metadata and controls
78 lines (72 loc) · 1.36 KB
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
local rules = {}
local strings = {}
for v in input:gmatch("[^\n]+") do
if v:match("%d") then
if v:match("%a") then
rules[tonumber(v:match("%d+"))] = v:match("%a")
print(v)
else
local rulen, rule = v:match("(%d+): (.*)")
local options = {}
for w in rule:gmatch("[^|]+") do
local set = {}
for x in w:gmatch("%d+") do
set[#set+1] = tonumber(x)
end
options[#options+1] = set
end
rules[tonumber(rulen)] = options
end
else
strings[#strings+1] = v
end
end
function f(s, rulen)
if type(rules[rulen]) == "string" then
if rules[rulen] == s:sub(1, 1) then
return s:sub(2)
end
else
for _, option in pairs(rules[rulen]) do
local r = s
for _, n in pairs(option) do
r = f(r, n)
if not r then break end
end
if r == "" or (r and rulen ~= 0) then return r end
end
end
end
local count = 0
for _, s in pairs(strings) do
if f(s, 0) then
count = count + 1
end
end
print(count) -- part 1
--8: 42 | 42 8
--11: 42 31 | 42 11 31
--42*n
--42*m 31*m
local count = 0
for _, s in pairs(strings) do
local count42, count31 = 0, 0
repeat
local r = f(s, 42)
if r then
s = r
count42 = count42 + 1
end
until not r
repeat
local r = f(s, 31)
if r then
s = r
count31 = count31 + 1
end
until not r
if s == "" and count42 - count31 > 0 and count31 > 0 then
count = count + 1
end
end
print(count) -- part 2