-
-
Save waynejo/31bb1d565c7ca9c4f24e5d69b8ca3f6a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.FileInputStream | |
import scala.annotation.{tailrec, targetName} | |
import scala.io.StdIn | |
case class Point(x: Int, y: Int) { | |
def +(that: Point): Point = Point(this.x + that.x, this.y + that.y) | |
} | |
case class Map(element: Vector[Vector[Int]]) { | |
@tailrec | |
private def _iterate[T](position: Point, delta: Point, start: Int, acc: T, iterate: (T, Int, Int) => T): T = { | |
if 0 > position.x || 0 > position.y || position.x >= element(0).size || position.y >= element.size then | |
acc | |
else | |
val target = element(position.y)(position.x) | |
val nextAcc = iterate(acc, start, target) | |
_iterate(position + delta, delta, start, nextAcc, iterate) | |
} | |
def iterateAndFold[T, R](acc: T, iterate: (T, Int, Int) => T, foldAcc: R, foldOp: (R, T) => R): Vector[Vector[R]] = { | |
element.zipWithIndex.map { case (row, y) => | |
row.zipWithIndex.map { case (v, x) => | |
val position = Point(x, y) | |
val start = element(y)(x) | |
Vector(Point(1, 0), Point(0, 1), Point(-1, 0), Point(0, -1)).map(delta => _iterate(position + delta, delta, start, acc, iterate)).foldLeft(foldAcc)(foldOp) | |
} | |
} | |
} | |
} | |
def solve8_1(input: Map): Int = | |
val visibility: Vector[Vector[Boolean]] = input.iterateAndFold(true, (acc, start, target) => acc && start > target, false, (acc, v) => acc || v) | |
visibility.map(_.count(_ == true)).sum | |
def solve8_2(input: Map): Int = | |
val visibility: Vector[Vector[Int]] = input.iterateAndFold((true, 0), (acc, start, target) => { | |
acc match { | |
case (true, v) => | |
if start > target then | |
(true, acc._2 + 1) | |
else | |
(false, acc._2 + 1) | |
case _ => | |
acc | |
} | |
}, 1, (acc, v) => acc * v._2) | |
visibility.map(_.max).max | |
@main def solve8(): Unit = | |
val in = new FileInputStream("example8-2.in") | |
System.setIn(in) | |
val inputs = Iterator.continually(StdIn.readLine()) | |
.takeWhile(line => null != line) | |
.map(line => line.map(_ - '0').toVector) | |
.toVector | |
val input = Map(inputs) | |
println(solve8_1(input)) | |
println(solve8_2(input)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment