-
-
Save waynejo/7d8927fa4c78a832c5d05b296e0e42d1 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) | |
def moved(direction: Char): Point = direction match { | |
case 'U' => this + Point(0, 1) | |
case 'D' => this + Point(0, -1) | |
case 'R' => this + Point(1, 0) | |
case 'L' => this + Point(-1, 0) | |
} | |
} | |
case class World(points: Vector[Point]) | |
case class Command(direction: Char, steps: Int) | |
def simulate(acc: Vector[World], commands: Vector[Command]): Vector[World] = | |
commands.headOption match | |
case Some(command) => | |
val nextCommand: Vector[Command] = if 1 < command.steps then | |
Vector(Command(command.direction, command.steps - 1)) ++ commands.tail | |
else | |
commands.tail | |
val world = acc.last | |
val movedHead = world.points.head.moved(command.direction) | |
val nextPoints = world.points.tail.foldLeft(Vector(movedHead)) { (acc, tail) => | |
val head = acc.last | |
val xDiff = (head.x - tail.x).abs | |
val yDiff = (head.y - tail.y).abs | |
if 1 >= xDiff && 1 >= yDiff then | |
acc :+ tail | |
else | |
val nextTail = tail + Point((head.x - tail.x) / (1 max xDiff), (head.y - tail.y) / (1 max yDiff)) | |
acc :+ nextTail | |
} | |
simulate(acc :+ World(nextPoints), nextCommand) | |
case _ => | |
acc | |
def solve9_1(commands: Vector[Command]): Int = | |
val world = World(Vector.fill(2)(Point(0, 0))) | |
simulate(Vector(world), commands).map(_.points.last).distinct.size | |
def solve9_2(commands: Vector[Command]): Int = | |
val world = World(Vector.fill(10)(Point(0, 0))) | |
simulate(Vector(world), commands).map(_.points.last).distinct.size | |
@main def solve9(): Unit = | |
val in = new FileInputStream("example9-2.in") | |
System.setIn(in) | |
val inputs = Iterator.continually(StdIn.readLine()) | |
.takeWhile(line => null != line) | |
.map(line => { | |
val Array(direction, steps) = line.split(" ") | |
Command(direction.head, steps.toInt) | |
}) | |
.toVector | |
println(solve9_1(inputs)) | |
println(solve9_2(inputs)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment