Skip to content

Instantly share code, notes, and snippets.

@waynejo
Last active December 31, 2021 12:07
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 waynejo/77d97f8fb629e98586013b24e72fa73b to your computer and use it in GitHub Desktop.
Save waynejo/77d97f8fb629e98586013b24e72fa73b to your computer and use it in GitHub Desktop.
import java.io.FileInputStream
import scala.annotation.tailrec
import scala.io.StdIn
case class Submarine(depth: Int = 0, position: Int = 0, aim: Int = 0)
def solve2_1(inputs: Vector[String]): Int = {
val submarine = inputs.foldLeft(Submarine()) { (submarine, x) =>
val Array(command, nString) = x.split(" ")
val n = nString.toInt
command match {
case "forward" =>
submarine.copy(position = submarine.position + n)
case "down" =>
submarine.copy(depth = submarine.depth + n)
case "up" =>
submarine.copy(depth = submarine.depth - n)
}
}
submarine.depth * submarine.position
}
def solve2_2(inputs: Vector[String]): Int = {
val submarine = inputs.foldLeft(Submarine()) { (submarine, x) =>
val Array(command, nString) = x.split(" ")
val n = nString.toInt
command match {
case "forward" =>
submarine.copy(position = submarine.position + n, depth = submarine.depth + submarine.aim * n)
case "down" =>
submarine.copy(aim = submarine.aim + n)
case "up" =>
submarine.copy(aim = submarine.aim - n)
}
}
submarine.depth * submarine.position
}
@main def solve2(): Unit =
val in = new FileInputStream("example2-2.in")
System.setIn(in)
val inputs = Iterator.continually(StdIn.readLine())
.takeWhile(line => null != line && line.trim.nonEmpty)
.toVector
println(solve2_1(inputs))
println(solve2_2(inputs))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment