DEV Community 👩‍💻👨‍💻

Marco Servetto
Marco Servetto

Posted on

Advent of code, day 3

Ok, day 3 part one was nice and simple. FIrst I defined a couple of utility static methods, then just rolled over the data.
In this code I managed to showcase a unique feature of 42 'for-in':
you can update the element under iteration!

Pow2 = {class method I (I that) =
  if that==0I 1I else 2I*This(that-1I) }
Is1 = {class method Bool(S that, I i) =
  that.startsWith(S"1" leftOffSet=i)}
MainPart1 = (
  input = Fs.Real.#$of().read(\"input")
  tot = I.List[0I;0I;0I;0I;0I;0I;0I;0I;0I;0I;0I;0I]
  var size = 0I
  for s in input.split(S.nl()) (
    size+=1I
    for var e in tot, i in Range(tot.size()) (
      if Is1(s i=i) e:=e+1I //update the value inside of 'tot'
      )
    )
  var gamma = 0I
  var epsilon = 0I
  for e in tot, i in Range(tot.size()).reverse() (
    if e+e>size gamma+=Pow2(i) 
    else      epsilon+=Pow2(i)
    )
  Debug(gamma*epsilon)
  )
Enter fullscreen mode Exit fullscreen mode

The second part, I found it involved in a boring way. I think there must have been a smarted way to solve it, but I could not find it. I had to read the description a couple of time to understand that I had to look for the most common bit in the REMAINING elements...

Part2 = {class method I (S that, Bool geq) = (
  res = S.List()(for s in that.split(S.nl()) \add(s))
  size = res.left().size()
  var remaining = res.size()
  for  i in Range(size) (
    if remaining==1I ( Break() )
    e = Match.Count()(for s in res if s!=S"" \add(Is1(s,i=i)))
    seek1 = ( if geq e+e>=remaining else e+e<remaining )
    for var s in res if s!=S"" && seek1!=Is1(s,i=i) (
      s:=S"" remaining-=1I 
      )
    )
  var resI = 0I
  for s in res if s!=S"" (
    for j in Range(size), i in Range(size).reverse() (
      if Is1(s,i=j) resI+=Pow2(i)
      )
    )
  resI
  )}
MainPart2 = (
  input = Fs.Real.#$of().read(\"input")
  ogr = Part2(input,geq=\.true())
  co2sr = Part2(input,geq=\.false())
  Debug(ogr*co2sr)
  )
Enter fullscreen mode Exit fullscreen mode

As you can see, I just end up calling the same function twice.
You can notice that I'm still unsure how to format my code:
for example I wrote

for var s in res if s!=S"" && seek1!=Is1(s,i=i) (
  s:=S"" remaining-=1I 
  )
Enter fullscreen mode Exit fullscreen mode

instead of the more conventional

for var s in res (
  if s!=S"" && seek1!=Is1(s,i=i) s:=S"" remaining-=1I 
  )
Enter fullscreen mode Exit fullscreen mode

or the even longer version with also the 'if' indented.
What would be more readable? and why?

Top comments (0)

Update Your DEV Experience Level:

Settings

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