DEV Community 👩‍💻👨‍💻

Marco Servetto
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]
Fs = Load:{reuse[L42.is/FileSystem]}

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()
  input = fs.read(\"input")
  imm crabs = Num.List()(for s in input.split(S",")
    \add(\(string=s.trim()))
    )
  min = Min(crabs)
  max = Max(crabs)
  imm costs=Num.List()(for i in Range(I(min) to=I(max)) 
    \add(Cost(crabs,pos=Num(i)))
    )
  minC=Min(costs)
  Debug(minC)
  )
Enter fullscreen mode Exit fullscreen mode

I'm also putting on my you tube channel a video discussing improved versions for the code I made this week.
(https://www.youtube.com/MarcoServetto)

Top comments (0)

Take a look at this:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. 🛠