2
1
Fork 0

Day 5: Add Lua solution

This commit is contained in:
Mia Herkt 2021-12-05 13:18:41 +01:00
parent 5fb0db17fb
commit 406e1fc632
Signed by: mia
GPG Key ID: 72E154B8622EC191
2 changed files with 77 additions and 0 deletions

33
05/solution_1.lua Normal file
View File

@ -0,0 +1,33 @@
#!/usr/bin/env lua
map = {}
for line in io.lines("input.txt") do
x0, y0, x1, y1 = string.match(line, "(%d+),(%d+) .+ (%d+),(%d+)")
x0 = tonumber(x0) x1 = tonumber(x1) y0 = tonumber(y0) y1 = tonumber(y1)
if x0 == x1 then
map[x0] = map[x0] or {}
if y0 > y1 then step = -1 else step = 1 end
for y = y0, y1, step do
map[x0][y] = (map[x0][y] or 0) + 1
end
elseif y0 == y1 then
if x0 > x1 then step = -1 else step = 1 end
for x = x0, x1, step do
map[x] = map[x] or {}
map[x][y0] = (map[x][y0] or 0) + 1
end
end
end
intersections = 0
for _, col in pairs(map) do
for _, f in pairs(col) do
if f > 1 then
intersections = intersections + 1
end
end
end
print("Answer:", intersections)

44
05/solution_2.lua Normal file
View File

@ -0,0 +1,44 @@
#!/usr/bin/env lua
map = {}
for line in io.lines("input.txt") do
x0, y0, x1, y1 = string.match(line, "(%d+),(%d+) .+ (%d+),(%d+)")
x0 = tonumber(x0) x1 = tonumber(x1) y0 = tonumber(y0) y1 = tonumber(y1)
if y0 > y1 then ystep = -1 else ystep = 1 end
if x0 > x1 then xstep = -1 else xstep = 1 end
if x0 == x1 then
map[x0] = map[x0] or {}
for y = y0, y1, ystep do
map[x0][y] = (map[x0][y] or 0) + 1
end
elseif y0 == y1 then
for x = x0, x1, xstep do
map[x] = map[x] or {}
map[x][y0] = (map[x][y0] or 0) + 1
end
else
x = x0 y = y0
while x ~= x1 and y ~= y1 do
map[x] = map[x] or {}
map[x][y] = (map[x][y] or 0) + 1
x = x + xstep
y = y + ystep
end
map[x] = map[x] or {}
map[x][y] = (map[x][y] or 0) + 1
end
end
intersections = 0
for _, col in pairs(map) do
for _, f in pairs(col) do
if f > 1 then
intersections = intersections + 1
end
end
end
print("Answer:", intersections)