This commit is contained in:
Paul-Henri Froidmont 2022-12-08 08:03:05 +01:00
parent 46b37c5bc1
commit 692ceb5adc
Signed by: phfroidmont
GPG key ID: BE948AFD7E7873BE
2 changed files with 148 additions and 0 deletions

49
aoc/src/Day8.scala Normal file
View file

@ -0,0 +1,49 @@
import scala.io.Source
import scala.collection.mutable
object Day8 extends App:
val input = Source
.fromURL(getClass.getResource("day8Input.txt"))
.mkString
.split('\n')
.map(_.map(_.asDigit).toVector)
.toVector
extension [T](list: IndexedSeq[T])
def takeUntil(predicate: T => Boolean): IndexedSeq[T] =
if list.indexWhere(predicate) == -1 then list
else list.take(list.indexWhere(predicate) + 1)
type Grid = Vector[Vector[Int]]
extension (grid: Grid)
def height = grid.length - 1
def width = grid(0).length - 1
def allPositions =
for
y <- 0 to grid.height
x <- 0 to grid.width
yield (x, y)
def isVisible(x: Int, y: Int): Boolean =
val value = grid(y)(x)
(0 until x).forall(offset => grid(y)(offset) < value) ||
(0 until y).forall(offset => grid(offset)(x) < value) ||
(x + 1 to width).forall(offset => grid(y)(offset) < value) ||
(y + 1 to height).forall(offset => grid(offset)(x) < value)
def computeScenicScore(x: Int, y: Int): Int =
val value = grid(y)(x)
(x - 1 to (0, -1)).takeUntil(offset => grid(y)(offset) >= value).length *
(y - 1 to (0, -1)).takeUntil(offset => grid(offset)(x) >= value).length *
(x + 1 to width).takeUntil(offset => grid(y)(offset) >= value).length *
(y + 1 to height).takeUntil(offset => grid(offset)(x) >= value).length
val part1 = input.allPositions.count(input.isVisible)
println(s"Part 1: $part1")
val part2 = input.allPositions.map(input.computeScenicScore).max
println(s"Part 2: $part2")
end Day8