Skip to content

Instantly share code, notes, and snippets.

@sungkmi
Last active December 31, 2021 12:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sungkmi/88db56b12b90fa9d33324bcd2aa1f21f to your computer and use it in GitHub Desktop.
Save sungkmi/88db56b12b90fa9d33324bcd2aa1f21f to your computer and use it in GitHub Desktop.
package lascala.aoc2021.day1_10.day2
case class Position(horizontal: Int, depth: Int)
extension (p: Position)
def step(command: String): Position =
val (operator, value) = parseCommand(command)
operator match
case "forward" => p.copy(horizontal = p.horizontal + value)
case "down" => p.copy(depth = p.depth + value)
case "up" => p.copy(depth = p.depth - value)
object Position:
val initial: Position = Position(0, 0)
case class AimPosition(aim: Int, horizontal: Int, depth: Int)
extension (a: AimPosition)
def step(command: String): AimPosition =
val (operator, value) = parseCommand(command)
operator match
case "down" => a.copy(aim = a.aim + value)
case "up" => a.copy(aim = a.aim - value)
case "forward" => a.copy(
horizontal = a.horizontal + value,
depth = a.depth + value * a.aim,
)
def parseCommand(command: String): (String, Int) =
val Array(operator, operand) = command.split(" ")
(operator, operand.toInt)
object AimPosition:
val initial: AimPosition = AimPosition(0, 0, 0)
def solve1(s: String): Int =
val commands = s.split("\n")
val finalPosition = commands.foldLeft(Position.initial)(_ step _)
finalPosition.horizontal * finalPosition.depth
def solve2(s: String): Int =
val commands = s.split("\n")
val finalPosition = commands.foldLeft(AimPosition.initial)(_ step _)
finalPosition.horizontal * finalPosition.depth
@main def part1: Unit =
val ans = solve1(input)
println(ans)
@main def part2: Unit =
val ans = solve2(input)
println(ans)
// val input = """forward 2
package lascala.aoc2021.day1_10.day2
import minitest.SimpleTestSuite
import hedgehog.minitest.HedgehogSupport
import hedgehog.*
object Day2Test extends SimpleTestSuite with HedgehogSupport:
val exampleInput: String = """forward 5
down 5
forward 8
up 3
down 8
forward 2"""
example("day2 - solve1") {
solve1(exampleInput) ==== 150
}
example("day2 - solve2") {
solve2(exampleInput) ==== 900
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment