feat: solve day 3 puzzle 2

This commit is contained in:
2025-12-03 13:15:45 +01:00
parent 3be58692ab
commit d0cc52fbda
4 changed files with 62 additions and 5 deletions

View File

@@ -1,7 +1,64 @@
local utils = require("utils")
local puzzle1 = require(SRC_PATH .. "/day03/puzzle1")
local puzzle2 = {}
local cache = {}
function puzzle2.findMaxJoltage(bank, joltages, n, startI)
startI = startI or 1
local key = bank:sub(startI) .. "-" .. tostring(n)
if cache[key] then
return cache[key]
end
local maxJoltage = 0
local maxDigit = 0
if startI > #joltages then
return nil
end
if n == 1 then
for i=startI, #joltages do
if joltages[i] > maxDigit then
maxDigit = joltages[i]
end
end
cache[key] = maxDigit
return maxDigit
end
local i = startI
while i <= #joltages do
local digit = joltages[i]
if digit > maxDigit then
local maxSuffix = puzzle2.findMaxJoltage(bank, joltages, n - 1, i + 1)
if maxSuffix ~= nil then
local joltage = tonumber(tostring(digit) .. tostring(maxSuffix))
if joltage > maxJoltage then
maxDigit = digit
maxJoltage = joltage
end
end
end
i = i + 1
end
if maxJoltage == 0 then
return nil
end
cache[key] = maxJoltage
return maxJoltage
end
function puzzle2.solve(input)
return 0
local banks = utils.splitLines(input)
local totalJoltage = 0
for _, bank in ipairs(banks) do
local joltages = puzzle1.bankJoltages(bank)
local max = puzzle2.findMaxJoltage(bank, joltages, 12)
totalJoltage = totalJoltage + max
end
return totalJoltage
end
return puzzle2

View File

@@ -147,7 +147,7 @@ function Day:execPuzzle(puzzleI, data, resultKey)
local result = puzzle.solve(data)
local t1 = os.epoch("local")
print(("(Executed in %.3fs)"):format((t1 - t0) / 1000))
print("Result:", result)
print(("Result: %.0f"):format(result))
self.results[resultKey] = result
self:saveResults()
end