57 lines
1.3 KiB
Lua
57 lines
1.3 KiB
Lua
io.input("test")
|
|
io.input("input")
|
|
|
|
|
|
function pos2index( pos )
|
|
return pos.x*10000 + pos.y
|
|
end
|
|
|
|
function constrain( n, min, max )
|
|
local min = min or -1
|
|
local max = max or 1
|
|
if n < min then return min
|
|
elseif n > max then return max
|
|
else return n
|
|
end
|
|
end
|
|
|
|
|
|
local head = { x=1, y=1 }
|
|
local tail = { x=1, y=1 }
|
|
local visited = { [pos2index(tail)] = true }
|
|
|
|
for line in io.lines() do
|
|
local dir, q = string.match(line, "^(%a) (%d+)$")
|
|
q = tonumber(q)
|
|
for step = 1,q do
|
|
if dir == "R" then
|
|
head.x = head.x + 1
|
|
elseif dir == "L" then
|
|
head.x = head.x - 1
|
|
elseif dir == "U" then
|
|
head.y = head.y + 1
|
|
elseif dir == "D" then
|
|
head.y = head.y - 1
|
|
end
|
|
|
|
local dif = { x=head.x-tail.x, y=head.y-tail.y }
|
|
if dif.x == 0 and math.abs(dif.y) > 1 then
|
|
tail.y = tail.y + constrain(dif.y)
|
|
elseif dif.y == 0 and math.abs(dif.x) > 1 then
|
|
tail.x = tail.x + constrain(dif.x)
|
|
elseif math.abs(dif.x)>1 or math.abs(dif.y)>1 then
|
|
tail.y = tail.y + constrain(dif.y)
|
|
tail.x = tail.x + constrain(dif.x)
|
|
end
|
|
print( tail.x, tail.y, head.x, head.y, dif.x, dif.y)
|
|
visited[ pos2index(tail) ] = true
|
|
end
|
|
end
|
|
|
|
local result = 0
|
|
for k, v in pairs(visited) do
|
|
print(k)
|
|
result = result + 1
|
|
end
|
|
print("part 1", result)
|