summaryrefslogtreecommitdiff
path: root/09/1.lua
diff options
context:
space:
mode:
authorAlex Pickering <alex@cogarr.net>2025-02-07 12:49:48 -0600
committerAlex Pickering <alex@cogarr.net>2025-02-07 12:49:48 -0600
commit3555be54c2abb8d5ece008a60dbdfbde0ffbddd7 (patch)
tree278876284d07118ecdea5c48cb6453f3122887f0 /09/1.lua
downloadadvent_of_code_2022-3555be54c2abb8d5ece008a60dbdfbde0ffbddd7.tar.gz
advent_of_code_2022-3555be54c2abb8d5ece008a60dbdfbde0ffbddd7.tar.bz2
advent_of_code_2022-3555be54c2abb8d5ece008a60dbdfbde0ffbddd7.zip
inital commitHEADmaster
Diffstat (limited to '09/1.lua')
-rw-r--r--09/1.lua48
1 files changed, 48 insertions, 0 deletions
diff --git a/09/1.lua b/09/1.lua
new file mode 100644
index 0000000..8757767
--- /dev/null
+++ b/09/1.lua
@@ -0,0 +1,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)