summaryrefslogtreecommitdiff
path: root/09/1.lua
blob: 87577677edee5dcf78391cc9aa25556aea45eb6c (plain)
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
local knots, tail_moved = {}, {}
for i = 1,10 do table.insert(knots,{1,1}) end
local directions = {
	R = {1,0},
	U = {0,1},
	L = {-1,0},
	D = {0,-1},
}
local sfmt = "%d - %d"
local motion = {}
for i = -2,2 do
	for j = -2, 2 do
		if math.abs(i)^2 + math.abs(j)^2 > 2 then
			motion[sfmt:format(i,j)] = {
				i == 0 and 0 or math.abs(i)/i,
				j == 0 and 0 or math.abs(j)/j
			}
		else
			motion[sfmt:format(i,j)] = {0,0}
		end
	end
end
local function insert_tail_pos()
	local tail = knots[#knots]
	tail_moved[string.format(sfmt,tail[1],tail[2])] = true
end
local function move_knot(knot,twords)
	local x,y = twords[1] - knot[1], twords[2] - knot[2]
	local direction = motion[string.format("%d - %d",x,y)]
	knot[1],knot[2] = knot[1] + direction[1], knot[2] + direction[2]
end
insert_tail_pos()
for line in io.lines() do
	local direction, steps = line:match("([RULD]) (%d+)")
	direction = directions[direction]
	for i = 1,steps do
		knots[1][1], knots[1][2] = knots[1][1] + direction[1], knots[1][2] + direction[2]
		for j = 2,#knots do
			move_knot(knots[j],knots[j-1])
			insert_tail_pos()
		end
	end
end
local tmr = {}
for p,_ in pairs(tail_moved) do
	table.insert(tmr,p)
end
print(#tmr)