aoc2024

Advent of Code 2024
Log | Files | Refs | README

Day2.scala (1430B)


      1 def day2_pt1(input: Iterator[String]): Int =
      2     input.count(line => safe(parse_line(line)))
      3 
      4 def day2_pt2(input: Iterator[String]): Int =
      5     input.count(line => 
      6         val pl = parse_line(line)
      7         if safe(pl) then 
      8           true
      9         else 
     10           // try removing one element from the list
     11           // I thought about being clever and starting only at the point where
     12           // we encounter a problem; but it's tricky to reason about; maybe the _first_ element
     13           // is wrong , but then the error shows up only in the comparison with element indexes 1:2
     14           // because the sign is incorrect or smth. Anyway, the dumb solution is fast enough
     15           List.range(0, pl.size).exists((n: Int) => 
     16             val pll = rm(pl, n)
     17             safe(pll)
     18           )
     19     )
     20 
     21 def rm(list: List[Int], n: Int): List[Int] =
     22     // The scala standard library doesn't have this, apparently becuase it's so inefficient
     23     // :shrug: I need it
     24     val (l1, l2) = list.splitAt(n)
     25     l1.appendedAll(l2.tail)
     26     
     27 def parse_line(line: String): List[Int] =
     28     line.split(" ").map(e => Integer.parseInt(e.strip())).toList
     29 
     30 def safe(list: List[Int]): Boolean =
     31     val incr = list(1) - list(0) > 0
     32     list.sliding(2).forall(w => safe(incr, w(0), w(1)))
     33 
     34 def safe(incr: Boolean, e1: Int, e2: Int): Boolean =
     35     val diff = e2 - e1
     36     val absDiff = Math.abs(diff)
     37     (diff > 0 == incr) && absDiff > 0 && absDiff <= 3