2020 day 12
This commit is contained in:
parent
0fa66344bd
commit
7e411a5e42
|
@ -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())
|
Loading…
Reference in New Issue