aoc2024

Advent of Code 2024
Log | Files | Refs | README

Day4.scala (1544B)


      1 import scala.util.matching.Regex
      2 
      3 
      4 def day4_pt1(input: Iterator[String]): Int =
      5     val re = new Regex("XMAS")
      6     slices(input.toList)
      7         .flatMap(s => List(s, s.reverse))
      8         .foldRight(0) { (s, c) => 
      9             c + re.findAllMatchIn(s).size
     10         }
     11 
     12 // Take slices in the 4 possible directions:
     13 // rows; columns, diagonal left, diagonal right
     14 def slices(list: List[String]): List[String] =
     15     val width = list(0).size
     16     val rows = list
     17     val cols: List[String] = List.range(0, width).map(n => list.map(s => s.charAt(n)).mkString)
     18     val diagL: List[String] = List.range(0, width*2-1).map(n => list.zipWithIndex.filter((s, ix) => n-ix >= 0 && n-ix < width).map((s, ix) => s.charAt(n-ix)).mkString)
     19     val diagR: List[String] = List.range(1-width, width).map(n => list.zipWithIndex.filter((s, ix) => n+ix >= 0 && n+ix < width).map((s, ix) => s.charAt(n+ix)).mkString)
     20     rows.appendedAll(cols).appendedAll(diagL).appendedAll(diagR)
     21 
     22 def day4_pt2(input: Iterator[String]): Int =
     23     val allowed = Set("MMASS", "SSAMM", "MSAMS", "SMASM")
     24     stars(input.toList)
     25         .count(s => allowed.contains(s))
     26 
     27 def stars(list: List[String]): List[String] =
     28     val width = list(0).size
     29     val height = list.size
     30     List.range(1, width-1)
     31         .flatMap(x => LazyList.continually(x).zip(List.range(1, height-1)))
     32         .map((x, y) => List(list(y-1).charAt(x-1), 
     33                 list(y-1).charAt(x+1), 
     34                 list(y).charAt(x), 
     35                 list(y+1).charAt(x-1),
     36                 list(y+1).charAt(x+1)).mkString)