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

  • Karmmah@lemmy.world
    link
    fedilink
    arrow-up
    1
    ·
    3 days 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))")