## DEV Community is a community of 787,688 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Marco Servetto

Posted on

# First week of advent of code.

Today was fun.
I did not remembered the formula for the summatory of 1,2,3,4..., so I computed it in the slow way.
Then, I could use 42 caching to speed the whole thing up, and still obtain a reasonable time in the end.
Here is the code:

``````reuse [L42.is/AdamsTowel]

Max ={class method Num (Num.List that)={
if that.size()==1I return that.left()
return that.left().max(Max(that.withoutLeft()))
}}
Min ={class method Num (Num.List that)={
if that.size()==1I return that.left()
return that.left().min(Min(that.withoutLeft()))
}}
Fuel=Data:{ Num dist,Num round
method Num res(Num dist,Num round)={
if dist==0Num return dist
if dist==1Num return round
return round+\res(dist=dist-1Num,round=round+1Num)
}
@Cache.Lazy method Num () =
\res(dist=this.dist(),round=this.round())
class method Num (Num dist) = This(dist=dist,round=1Num)<:This()
//class method Num(Num dist)=(dist*(dist+1Num))/2Num
//If I just remembered the formula commented above
//I could have avoided the caching stuff...
}
Cost ={class method Num(Num.List that, Num pos)=(
var tot = 0Num
for n in that (
var abs = n-pos
if abs<0Num ( abs:=abs*Num"-1" )
tot+=Fuel(dist=abs)
)
tot
)}
Main=(
fs = Fs.Real.#\$of()
imm crabs = Num.List()(for s in input.split(S",")
)
min = Min(crabs)
max = Max(crabs)
imm costs=Num.List()(for i in Range(I(min) to=I(max))