Skip to content

Commit

Permalink
Day 14: optimize
Browse files Browse the repository at this point in the history
  • Loading branch information
michaeladler committed Dec 14, 2024
1 parent 764db8c commit 1c652e3
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 25 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,4 @@
| 11 | Lua | 50.3ms |
| 12 | Lua | 19.9ms |
| 13 | Lua | 2.31ms |
| 14 | Lua | 7480ms |
| 14 | Lua | 610ms |
41 changes: 21 additions & 20 deletions src/day14/day14.lua
Original file line number Diff line number Diff line change
Expand Up @@ -56,39 +56,40 @@ M.solve = function(input, width, height)
local part1 = top_left * top_right * lower_left * lower_right

-- part2
local render = function()
local is_tree = function()
local map = {}
for y = 0, height - 1 do
map[y] = {}
end

for _, rbt in pairs(robots) do
local row = map[rbt.y] or {}
row[rbt.x] = (row[rbt.x] or 0) + 1
map[rbt.y] = row
map[rbt.y][rbt.x] = "#"
end

local lines = {}
for y = 0, height - 1 do
local s = ""
-- look for "##########"
local count = 0
for x = 0, width - 1 do
local count = (map[y] or {})[x]
if count then
s = s .. "#"
else
s = s .. "."
if map[y][x] == "#" then
count = count + 1
else -- reset count
count = 0
end
if count == 10 then
return true
end
end
table.insert(lines, s)
end
return lines

return false
end

local tree_pattern = string.rep("#", 10)
local part2
for i = 101, 1000000000 do
for i = 101, 10000 do
advance()
for _, line in ipairs(render()) do
if line:find(tree_pattern) then
part2 = i
goto done
end
if is_tree() then
part2 = i
goto done
end
end
::done::
Expand Down
5 changes: 1 addition & 4 deletions src/day14/day14_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,9 @@ p=7,3 v=-1,2
p=2,4 v=2,-3
p=9,5 v=-3,-3
]]
local part1, part2 = day14.solve(input, 11, 7)
local part1, _ = day14.solve(input, 11, 7)
it("part1", function()
assert.are.equal(12, part1)
end)
it("part2", function()
assert.are.equal(0, part2)
end)
end)
end)

0 comments on commit 1c652e3

Please sign in to comment.