1
0
Fork 0

2020 day 12

This commit is contained in:
Lucidiot 2020-12-12 06:49:36 +01:00
parent 0fa66344bd
commit 7e411a5e42
Signed by: lucidiot
GPG Key ID: 3358C1CA6906FB8D
2 changed files with 65 additions and 1 deletions

64
2020/12/day12.lua Normal file
View File

@ -0,0 +1,64 @@
local parsed = {}
for line in io.lines() do
table.insert(parsed, {line:sub(1, 1), tonumber(line:sub(2))})
end
-- Ship/waypoint position and direction
local e, n, dir_e, dir_n = 0, 0, 1, 0
-- Rotates the ship clockwise.
local function rotate_part1(value)
for _ = 1, value / 90 do
if dir_e == 0 then
-- Switching from North to East or South to West
dir_n, dir_e = dir_e, dir_n
else
-- Switching from East to South or West to North
dir_n, dir_e = -dir_e, 0
end
end
end
local functions = {
N=function (value) n = n + value end,
S=function (value) n = n - value end,
E=function (value) e = e + value end,
W=function (value) e = e - value end,
F=function (value) e, n = e + dir_e * value, n + dir_n * value end,
R=rotate_part1,
L=function (value) rotate_part1(360-value) end
}
local function run()
for _, instruction in ipairs(parsed) do
functions[instruction[1]](instruction[2])
end
return math.abs(e) + math.abs(n)
end
print(run())
--[[
Update the functions and state for part 2
Here, dir_ variables are the waypoint itself.
NSEW change the waypoint instead of moving the ship.
--]]
e, n, dir_e, dir_n = 0, 0, 10, 1
-- Rotate the waypoint around the ship clockwise.
local function rotate_part2(value)
for _ = 1, value / 90 do
dir_n, dir_e = -dir_e, dir_n
end
end
functions = {
N=function (value) dir_n = dir_n + value end,
S=function (value) dir_n = dir_n - value end,
E=function (value) dir_e = dir_e + value end,
W=function (value) dir_e = dir_e - value end,
F=function (value) e, n = e + dir_e * value, n + dir_n * value end,
R=rotate_part2,
L=function (value) rotate_part2(360-value) end
}
print(run())

View File

@ -22,7 +22,7 @@ is acceptable; anything goes as long as I solve it myself!
9 ██ ██
10 ██ ██ ██
11 ██ ██ ██
12 ██ ██
12 ██ ██ ██
13 ██
14 ██ ██
15 ██