This commit is contained in:
Paul-Henri Froidmont 2022-12-09 06:58:18 +01:00
parent 692ceb5adc
commit c3027abccc
Signed by: phfroidmont
GPG key ID: BE948AFD7E7873BE
2 changed files with 2044 additions and 0 deletions

44
aoc/src/Day9.scala Normal file
View file

@ -0,0 +1,44 @@
import scala.io.Source
import scala.collection.mutable
object Day9 extends App:
val input = Source
.fromURL(getClass.getResource("day9Input.txt"))
.mkString
.split('\n')
.toList
.map(_.split(" "))
.flatMap { case Array(d, moves) => Array.fill(moves.toInt)(d) }
.map {
case "R" => (1, 0)
case "L" => (-1, 0)
case "D" => (0, 1)
case "U" => (0, -1)
}
def followPrevious(headPos: (Int, Int), tailPos: (Int, Int)): (Int, Int) =
val offsetX = headPos._1 - tailPos._1
val offsetY = headPos._2 - tailPos._2
if Math.abs(offsetX) <= 1 && Math.abs(offsetY) <= 1 then tailPos
else
val xMove = if offsetX > 0 then 1 else -1
val yMove = if offsetY > 0 then 1 else -1
(
if Math.abs(offsetX) > 0 then tailPos._1 + xMove else tailPos._1,
if Math.abs(offsetY) > 0 then tailPos._2 + yMove else tailPos._2
)
def computeRopePositions(ropeLength: Int): List[List[(Int, Int)]] =
input.scanLeft(List.fill(ropeLength)((0, 0))) { (rope, change) =>
rope.tail.scanLeft((rope.head._1 + change._1, rope.head._2 + change._2))(
(node, previousPos) => followPrevious(node, previousPos)
)
}
val part1 = computeRopePositions(2).map(_.last).distinct.length
println(s"Part 1: $part1")
val part2 = computeRopePositions(10).map(_.last).distinct.length
println(s"Part 2: $part2")
end Day9