Skip to content

Commit bc36f49

Browse files
committed
2025: Optimize
1 parent 92b55a2 commit bc36f49

File tree

1 file changed

+28
-39
lines changed

1 file changed

+28
-39
lines changed

2025/src/day02_spec.lua

Lines changed: 28 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -24,52 +24,41 @@ bstd.it("chuncked", function()
2424
bstd.assert.same(insp(chuncked('112233', 3)), '{ "112", "233" }')
2525
end)
2626

27-
local fn_day00_part1 = function()
28-
local input = util.load_input("02")[1]
29-
30-
local ranges = util.stringsplit(input, ',')
27+
local sum_of_invalid = function(fn_filter)
28+
local input = util.load_input("02")
29+
local ranges = util.stringsplit(input[1], ',')
3130

32-
local invalid = fun.iter(ranges)
33-
:map(function(x)
31+
return fun.iter(ranges)
32+
:foldl(function(acc, x)
3433
local p1, p2 = table.unpack(util.stringsplit(x, '-'))
35-
return fun.range(tonumber(p1), tonumber(p2))
36-
:filter(function (y)
37-
if #tostring(y) % 2 ~= 0 then return false end
38-
local s = tostring(y)
39-
local c1, c2 = table.unpack(chuncked(s, #s / 2))
40-
return c1 == c2
41-
end)
42-
:map(function(y) return tonumber(y) end)
43-
:sum()
44-
end)
45-
:sum()
34+
return acc + fun.range(tonumber(p1), tonumber(p2))
35+
:filter(function (y) return fn_filter(y) end)
36+
:sum(function(y) return y end)
37+
end, 0)
38+
end
39+
40+
local fn_day00_part1 = function()
41+
local invalid = sum_of_invalid(function (y)
42+
local s = tostring(y)
43+
if #s % 2 ~= 0 then return false end
44+
local c1, c2 = table.unpack(chuncked(s, #s / 2))
45+
return c1 == c2
46+
end)
4647

4748
bstd.assert.same(19605500130, invalid)
4849
end
4950

5051
local fn_day00_part2 = function()
51-
local input = util.load_input("02")[1]
52-
53-
local ranges = util.stringsplit(input, ',')
54-
55-
local invalid = fun.iter(ranges)
56-
:map(function(x)
57-
local p1, p2 = table.unpack(util.stringsplit(x, '-'))
58-
return fun.range(tonumber(p1), tonumber(p2))
59-
:filter(function(y)
60-
local s = tostring(y)
61-
for _, p in fun.range(1, #s / 2) do
62-
if #s > 1 and #s % p == 0 then
63-
local chuncks = chuncked(s, p)
64-
local same = fun.all(function(a) return a == chuncks[1] end, chuncks)
65-
if same == true then return true end
66-
end
67-
end
68-
end)
69-
:map(function(y) return tonumber(y) end)
70-
:sum()
71-
end)
72-
:sum()
52+
local invalid = sum_of_invalid(function(y)
53+
local s = tostring(y)
54+
for p in fun.range(#s / 2) do
55+
if #s > 1 and #s % p == 0 then
56+
local chuncks = chuncked(s, p)
57+
local same = fun.all(function(a) return a == chuncks[1] end, chuncks)
58+
if same == true then return true end
59+
end
60+
end
61+
end)
7362

7463
bstd.assert.same(36862281418, invalid)
7564
end

0 commit comments

Comments
 (0)