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 []
Fs = Load:{reuse[]}

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 () = 
  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" )
  fs = Fs.Real.#$of()
  input =\"input")
  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)) 
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.

Top comments (0)