Skip to content

Commit

Permalink
Add solution for day 7
Browse files Browse the repository at this point in the history
FrederikSchnack committed Dec 7, 2024

Verified

This commit was signed with the committer’s verified signature. The key has expired.
aymanbagabas Ayman Bagabas
1 parent 0c6821f commit 0e4a93d
Showing 4 changed files with 70 additions and 3 deletions.
2 changes: 1 addition & 1 deletion inputs
2 changes: 1 addition & 1 deletion solutions/2024/src/AdventOfCode24.jl
Original file line number Diff line number Diff line change
@@ -8,7 +8,7 @@ module AdventOfCode24
readInput(day::Int) = AdventOfCode.readInput(day, year)
export readInput

solvedDays = [1, 2, 3, 4, 5, 6]
solvedDays = [1, 2, 3, 4, 5, 6, 7]

# Include the source files:
for day in solvedDays
63 changes: 63 additions & 0 deletions solutions/2024/src/day07.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
module Day07
using ..AdventOfCode24

"""
day07()
Solves the two puzzles of day 07.
"""

function day07(input::String = readInput(07))
lines = split(input, "\n")

s0 = 0
s1 = 0

for l in lines
res = parse(Int, match(r"(\d+):", l).captures[1])
args = [parse.(Int, m.captures[1]) for m in eachmatch(r"\s(\d+)", l)]

if is_valid(res, args)
s0 += res
s1 += res
elseif is_valid(res, args, true)
s1 += res
end

end

return [s0, s1]
end

function |(l::Int, r::Int)
return l * 10^(floor(Int,log10(r))+1) + r
end

function is_valid(res::Int, args::Vector{Int}, concat::Bool=false)

stack = [(args[1], args[2], 2, +),
(args[1], args[2], 2, *)]

concat && push!(stack, (args[1], args[2], 2, |))

while !isempty(stack)
l, r, i, op = pop!(stack)
ans = op(l, r)

if res == ans && i == length(args)
return true
elseif res < ans || i == length(args)
continue
else
push!(stack, (ans, args[i+1], i+1, +))
push!(stack, (ans, args[i+1], i+1, *))
concat && push!(stack, (ans, args[i+1], i+1, |))
end
end

return false

end


end
6 changes: 5 additions & 1 deletion solutions/2024/test/runtests.jl
Original file line number Diff line number Diff line change
@@ -20,5 +20,9 @@ end
@test AdventOfCode24.Day05.day05() == [5651, 4743]
end
@testset "Day 06" begin
@test AdventOfCode24.Day06.day06() == [s0, s1]
@test AdventOfCode24.Day06.day06() == [5531, 2165]
end

@testset "Day 07" begin
@test AdventOfCode24.Day07.day07() == [975671981569, 223472064194845]
end

0 comments on commit 0e4a93d

Please sign in to comment.