Skip to content

Commit

Permalink
refactor: use iterator
Browse files Browse the repository at this point in the history
easier on memory
  • Loading branch information
scarf005 committed Dec 4, 2024
1 parent 415b2cd commit 4d06cef
Showing 1 changed file with 13 additions and 14 deletions.
27 changes: 13 additions & 14 deletions 2024/day04.scala
Original file line number Diff line number Diff line change
Expand Up @@ -4,32 +4,31 @@ import prelude.*
import utils.Size

extension [A](xss: Seq[Seq[A]])
def rightDiagonal(size: Int): Seq[Seq[A]] = for
y <- 0 to xss.size - size
x <- size - 1 until xss(0).size
def rightDiagonal(size: Int): Iterator[Seq[A]] = for
y <- (0 to xss.size - size).iterator
x <- (size - 1 until xss(0).size).iterator
yield (for i <- 0 until size yield xss(y + i)(x - i))

def leftDiagonal(size: Int): Seq[Seq[A]] = for
y <- 0 to xss.size - size
x <- 0 to xss(0).size - size
def leftDiagonal(size: Int): Iterator[Seq[A]] = for
y <- (0 to xss.size - size).iterator
x <- (0 to xss(0).size - size).iterator
yield (for i <- 0 until size yield xss(y + i)(x + i))

def rects(size: Size): Seq[Seq[Seq[A]]] =
for
y <- 0 to xss.size - size.height
x <- 0 to xss(0).size - size.width
yield xss.slice(y, y + size.height).map(_.slice(x, x + size.width))
def rects(size: Size): Iterator[Seq[Seq[A]]] = for
y <- (0 to xss.size - size.height).iterator
x <- (0 to xss(0).size - size.width).iterator
yield xss.slice(y, y + size.height).map(_.slice(x, x + size.width))

def anyway(x: String)(y: String): Boolean = x == y || x.reverse == y

def part1(xxs: Seq[Seq[Char]]): Int =
def part1(xss: Seq[Seq[Char]]): Int =
def countOccurances(xs: Seq[Char]) =
xs.mkString.sliding(4).count(anyway("XMAS"))

(xxs ++ xxs.transpose ++ xxs.rightDiagonal(4) ++ xxs.leftDiagonal(4))
(xss ++ xss.transpose ++ xss.rightDiagonal(4) ++ xss.leftDiagonal(4))
.sumBy(countOccurances)

def part2(xxs: Seq[Seq[Char]]): Int = xxs.rects(Size(3, 3)).count {
def part2(xss: Seq[Seq[Char]]): Int = xss.rects(Size(3, 3)).count {
case Seq(
Seq(a, _, b),
Seq(_, c, _),
Expand Down

0 comments on commit 4d06cef

Please sign in to comment.