-
-
Save waynejo/77d97f8fb629e98586013b24e72fa73b 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 | |
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