Skip to content

Instantly share code, notes, and snippets.

@tong92
Created March 10, 2023 13:40
Show Gist options
  • Save tong92/c42d5d8dc8cc5b3bc1d2e4b4f2687f6f to your computer and use it in GitHub Desktop.
Save tong92/c42d5d8dc8cc5b3bc1d2e4b4f2687f6f to your computer and use it in GitHub Desktop.
aoc 2022 9
import scala.io.Source
case class Point(x: Int, y: Int)
object Point:
def move(h: Point, t: Point, n: Point) =
val head = Point(h.x + n.x, h.y + n.y)
(head.x - t.x, head.y - t.y) match
case (2, 2) => (head, Point(head.x - 1, head.y - 1))
case (-2, 2) => (head, Point(head.x + 1, head.y - 1))
case (2, -2) => (head, Point(head.x - 1, head.y + 1))
case (-2, -2) => (head, Point(head.x + 1, head.y + 1))
case (2, _) => (head, Point(head.x - 1, head.y))
case (-2, _) => (head, Point(head.x + 1, head.y))
case (_, 2) => (head, Point(head.x, head.y - 1))
case (_, -2) => (head, Point(head.x, head.y + 1))
case _ => (head, t)
def move(rs: List[Point], n: Point): List[Point] = rs match
case Nil => Nil
case (h :: Nil) => rs
case (h :: t :: rest) =>
Point.move(h, t, n) match
case (a, b) => a :: Point.move(b :: rest, Point(0, 0))
def moveRope(h: Point, t: Point, action: (Point, Int), result: List[Point]): (Point, Point, List[Point]) =
action match
case (_, 0) => (h, t, result)
case (p, n) =>
val res = Point.move(h, t, p)
moveRope(res._1, res._2, (p, n - 1), res._2 :: result)
def moveRope(ropes: List[Point], action: (Point, Int), result: List[Point]): (List[Point], List[Point]) =
action match
case (_, 0) => (ropes, result)
case (p, n) =>
val res = Point.move(ropes, p)
moveRope(res, (p, n - 1), res.last :: result)
def action(s: String): (Point, Int) =
val command = s.split(" ")
val action = command(0) match
case "U" => Point(0, 1)
case "D" => Point(0, -1)
case "L" => Point(-1, 0)
case "R" => Point(1, 0)
(action, command(1).toInt)
def ans1(xs: List[String]): Int =
val x = xs.foldLeft((Point(0, 0), Point(0, 0), List(Point(0, 0))))(
(acc, x) => acc match
case (h, t, res) => moveRope(h, t, action(x), res)
)
x._3.toSet.size
def ans2(xs: List[String]): Int =
val f = List(Point(0, 0),Point(0, 0),Point(0, 0),Point(0, 0),Point(0, 0),Point(0, 0),Point(0, 0),Point(0, 0),Point(0, 0),Point(0, 0))
val x = xs.foldLeft((f, List[Point]()))(
(acc, x) => acc match
case (ropes, res) => moveRope(ropes, action(x), res)
)
x._2.toSet.size
def solve =
val input = Source.fromFile("day9.txt").getLines.toList
println(ans1(input))
println(ans2(input))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment