-
-
Save waynejo/83311acfa65107c4b67b4a2f975e004c 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.io.StdIn | |
case class Point(x: Int, y: Int): | |
def fold(axis: Char, v: Int): Point = | |
axis match | |
case 'x' => | |
copy(x = if v < x then v - (x - v) else x) | |
case _ => | |
copy(y = if v < y then v - (y - v) else y) | |
def solve13_1(points: Vector[Point], folds: Vector[(Char, Int)]): Int = | |
val (axis, v) = folds.head | |
points.map(_.fold(axis, v)).toSet.size | |
def solve13_2(points: Vector[Point], folds: Vector[(Char, Int)]): String = | |
val foldedPoints = folds.foldLeft(points)((acc, x) => acc.map(_.fold(x._1, x._2))) | |
val dots = Array.fill[Char](foldedPoints.map(_.y).max + 1, foldedPoints.map(_.x).max + 1)(' ') | |
val result = foldedPoints.foldLeft(dots)((acc, p) => acc.updated(p.y, acc(p.y).updated(p.x, '.'))) | |
result.map(_.mkString).mkString("\n") | |
@main def solve13(): Unit = | |
val in = new FileInputStream("example13-2.in") | |
System.setIn(in) | |
val inputs = Iterator.continually(StdIn.readLine()) | |
.takeWhile(line => null != line && line.trim.nonEmpty) | |
.map(_.split(',')) | |
.map { case Array(x, y) => Point(x.toInt, y.toInt) } | |
.toVector | |
val foldInputs = Iterator.continually(StdIn.readLine()) | |
.takeWhile(line => null != line && line.trim.nonEmpty) | |
.map(_.split(' ').last.split("=")) | |
.map { case Array(x, y) => (x.toCharArray.head, y.toInt) } | |
.toVector | |
println(solve13_1(inputs, foldInputs)) | |
println(solve13_2(inputs, foldInputs)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment