-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2020_day23.lua
More file actions
110 lines (106 loc) · 2.05 KB
/
Copy path2020_day23.lua
File metadata and controls
110 lines (106 loc) · 2.05 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
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
local t = {}
for i = 1, #input do
t[i] = tonumber(input:sub(i, i))
end
local function remove(i)
if i > #t then
return remove(i - #t)
end
return table.remove(t, i)
end
local t2 = {table.unpack(t)}
local current = t[1]
local size = #t
for step = 1, 100 do
local index
for i = 1, #t do
if t[i] == current then
index = i
break
end
end
local a, b, c = remove(index+1)
if index+1>#t then
b=remove(1)
else
b=remove(index+1)
end
if index+1>#t then
c=remove(1)
else
c=remove(index+1)
end
for i = current-1, -math.huge, -1 do
if i < 1 then
i = i + size
end
if i ~= a and i ~= b and i ~= c then
local foundindex
for j = 1, #t do
if t[j] == i then
foundindex = j
break
end
end
table.insert(t, (foundindex + 1-1)%size+1, a)
table.insert(t, (foundindex + 2-1)%size+1, b)
table.insert(t, (foundindex + 3-1)%size+1, c)
break
end
end
for i = 1, #t do
if t[i] == current then
current = t[i%#t+1]
break
end
end
end
print(table.concat(t):rep(2):match("1(.+)1")) -- part 1
t = t2
local links = {}
local references = {}
for i = 1, size do
links[i] = {value = t[i]}
references[t[i]] = links[i]
end
for i = 1, size-1 do
links[i].next = links[i+1]
links[i+1].previous = links[i]
end
local lastlink = links[size]
for i = size+1, 1e6 do
lastlink = {value = i, previous = lastlink}
lastlink.previous.next = lastlink
references[i] = lastlink
end
lastlink.next, links[1].previous = links[1], lastlink
local current = links[1]
for step = 1, 1e7 do
local index
for i = 1, #t do
if t[i] == current then
index = i
break
end
end
local a = current.next
local b = a.next
local c = b.next
local d = c.next
for i = current.value-1, -math.huge, -1 do
if i < 1 then
i = i + 1e6
end
if i ~= a.value and i ~= b.value and i ~= c.value then
local link = references[i]
c.next, link.next.previous = link.next, c
link.next, a.previous = a, link
break
end
end
current.next = d
d.previous = current
current = d
end
local link = references[1]
print(link.next.value * link.next.next.value) -- part 2