feat: solve day 5 puzzle 2

This commit is contained in:
2025-12-05 11:55:54 +01:00
parent 80f797d4b9
commit bd36baa1ec
3 changed files with 44 additions and 4 deletions

View File

@@ -8,10 +8,10 @@ This project can also be run using the amazing [CraftOS-PC emulator](https://git
## Progress ## Progress
<!-- calendar-start --> <!-- calendar-start -->
#### Stars: 9/24 #### Stars: 10/24
|Mon|Tue|Wed|Thu|Fri|Sat|Sun| |Mon|Tue|Wed|Thu|Fri|Sat|Sun|
|:-:|:-:|:-:|:-:|:-:|:-:|:-:| |:-:|:-:|:-:|:-:|:-:|:-:|:-:|
|1<br>:star::star:|2<br>:star::star:|3<br>:star::star:|4<br>:star::star:|5<br>:star:|6<br>|7<br>| |1<br>:star::star:|2<br>:star::star:|3<br>:star::star:|4<br>:star::star:|5<br>:star::star:|6<br>|7<br>|
|8<br>|9<br>|10<br>|11<br>|12<br>||| |8<br>|9<br>|10<br>|11<br>|12<br>|||
<!-- calendar-end --> <!-- calendar-end -->

View File

@@ -17,7 +17,7 @@
}, },
"day05": { "day05": {
"puzzle1": true, "puzzle1": true,
"puzzle2": false "puzzle2": true
}, },
"day06": { "day06": {
"puzzle1": false, "puzzle1": false,

View File

@@ -1,7 +1,47 @@
local strings = require "cc.strings"
local puzzle2 = {} local puzzle2 = {}
function puzzle2.solve(input) function puzzle2.solve(input)
return 0 local lines = strings.split(input, "\n")
local bounds = {}
for _, line in ipairs(lines) do
if line == "" then
break
end
local min, max = line:match("(%d+)%-(%d+)")
min = tonumber(min)
max = tonumber(max)
table.insert(bounds, {i=min, type="start"})
table.insert(bounds, {i=max, type="end"})
end
table.sort(bounds, function (a, b)
if a.i == b.i then
return a.type == "start" and b.type == "end"
end
return a.i < b.i
end)
local totalFresh = 0
local min = 0
local balance = 0
for _, bound in ipairs(bounds) do
if bound.type == "start" then
if balance == 0 then
min = bound.i
end
balance = balance + 1
else
balance = balance - 1
if balance == 0 then
totalFresh = totalFresh + bound.i - min + 1
end
end
end
return totalFresh
end end
return puzzle2 return puzzle2