From 1c652e36ba574d8cd80973ccd50274e5777c6ef8 Mon Sep 17 00:00:00 2001 From: Michael Adler Date: Sat, 14 Dec 2024 19:10:50 +0100 Subject: [PATCH] Day 14: optimize --- README.md | 2 +- src/day14/day14.lua | 41 ++++++++++++++++++++-------------------- src/day14/day14_spec.lua | 5 +---- 3 files changed, 23 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 494ead7..a4557a9 100644 --- a/README.md +++ b/README.md @@ -20,4 +20,4 @@ | 11 | Lua | 50.3ms | | 12 | Lua | 19.9ms | | 13 | Lua | 2.31ms | -| 14 | Lua | 7480ms | +| 14 | Lua | 610ms | diff --git a/src/day14/day14.lua b/src/day14/day14.lua index 1bd4ad1..a0f9844 100644 --- a/src/day14/day14.lua +++ b/src/day14/day14.lua @@ -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:: diff --git a/src/day14/day14_spec.lua b/src/day14/day14_spec.lua index 41393f7..35d3e9e 100644 --- a/src/day14/day14_spec.lua +++ b/src/day14/day14_spec.lua @@ -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)