-
Notifications
You must be signed in to change notification settings - Fork 1
/
day_5.lua
76 lines (64 loc) · 1.78 KB
/
day_5.lua
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
local eio = require "libs.eio"
local profile = require "libs.profile"
local sequence = require "libs.sequence"
local input = eio.lines()
local printf = eio.printf
local sub = string.sub
local find = sequence.find
local equals = sequence.equals
local match = string.match
local concat = table.concat
local move = table.move
profile.start()
local nils = {}
local blank = find(equals(""), input)
local function parseStacks ()
local stacks = {}
for j = 2, #input[blank - 1], 4 do
local stack = {}
for i = blank - 2, 1, -1 do
local c = sub(input[i], j, j)
if c == " " then
break
end
stack[#stack + 1] = c
end
stacks[#stacks + 1] = stack
end
return stacks
end
local function parseMove (line)
return match(line, "move (%d+) from (%d) to (%d)")
end
local function tops (stacks)
local ts = {}
for i = 1, #stacks do
local stack = stacks[i]
ts[#ts + 1] = stack[#stack]
end
return concat(ts)
end
local function crateMover9000 (howMany, from, to)
for _ = 1, howMany do
to[#to + 1] = from[#from]
from[#from] = nil
end
end
local function crateMover9001 (howMany, from, to)
local fromIdx = #from - howMany + 1
move(from, fromIdx, #from, #to + 1, to)
move(nils, 1, howMany, fromIdx, from)
end
local function moveCrates (mover)
local stacks = parseStacks()
for i = blank + 1, #input do
local howMany, from, to = parseMove(input[i])
mover(howMany, stacks[tonumber(from)], stacks[tonumber(to)])
end
return tops(stacks)
end
local answer1 = moveCrates(crateMover9000)
printf("Part 1: %s\n", answer1)
local answer2 = moveCrates(crateMover9001)
printf("Part 2: %s\n", answer2)
return answer1, answer2, profile.finish()