this post was submitted on 07 Dec 2024
22 points (89.3% liked)

Advent Of Code

987 readers
8 users here now

An unofficial home for the advent of code community on programming.dev!

Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

AoC 2024

Solution Threads

M T W T F S S
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25

Rules/Guidelines

Relevant Communities

Relevant Links

Credits

Icon base by Lorc under CC BY 3.0 with modifications to add a gradient

console.log('Hello World')

founded 1 year ago
MODERATORS
 

Day 7: Bridge Repair

Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • You can send code in code blocks by using three backticks, the code, and then three backticks or use something such as https://topaz.github.io/paste/ if you prefer sending it through a URL

FAQ

(page 2) 3 comments
sorted by: hot top controversial new old
[โ€“] Karmmah@lemmy.world 1 points 2 weeks ago

Julia

Took quite some time to debug but in the end I think it's a nice solution using base 2 and 3 numbers counting up to check all operator combinations.

Code

function readInput(inputFile::String)::Vector{Vector{Int}}
	f = open(inputFile,"r")
	lines::Vector{String} = readlines(f)
	close(f)
	equations::Vector{Vector{Int}} = []
	function getValues(line::String)
		return map(sp->parse(Int,sp),(sp=split(line," ");sp[1]=sp[1][1:end-1];sp))
	end
	map(l->push!(equations,getValues(l)),lines)
	return equations
end

function checkEq(eq::Vector{Int},withConCat::Bool)::Bool
	function calcEq(eq::Vector{Int},operators::Vector{Int},withConCat::Bool)::Int
		res::Int = eq[2]
		for (i,op) in enumerate(operators)
			if op == 0 #+
				res += eq[i+2]
			elseif op ==1 #*
				res *= eq[i+2]
			else #op==2 ||
				res = parse(Int,string(res)*string(eq[i+2]))
			end
		end
		return res
	end
	opInt::Int = 0
	operators = Vector{Int}(undef,length(eq)-2)
	while opInt < (withConCat ? 3^(length(eq)-2) : 2^(length(eq)-2))
		withConCat==true ? operators=digits(opInt,base=3,pad=length(eq)-2) : operators=digits(opInt,base=2,pad=length(eq)-2)
		#calcEq(eq,operators,withConCat)==eq[1] ? (return true) : opInt -= 1
		calcEq(eq,operators,withConCat)==eq[1] ? (return true) : opInt += 1
	end
	return false
end

function calcTotCalRes(equations::Vector{Vector{Int}},withConCat::Bool)::Int
	totCalRes::Int = 0
	for e in equations
		checkEq(e,withConCat) ? totCalRes+=e[1] : nothing
	end
	return totCalRes
end

@info "Part 1"
println("result: $(calcTotCalRes(readInput("day07Input"),false))")
@info "Part 2"
println("result: $(calcTotCalRes(readInput("day07Input"),true))")

load more comments
view more: โ€น prev next โ€บ