Skip to content

Instantly share code, notes, and snippets.

@pcalcao
Created December 29, 2021 17:55
Show Gist options
  • Save pcalcao/9fb75f273bd7a1c5dc4dbd98c15ef4c9 to your computer and use it in GitHub Desktop.
Save pcalcao/9fb75f273bd7a1c5dc4dbd98c15ef4c9 to your computer and use it in GitHub Desktop.
package advent
import adventutil.io._
import scala.annotation.tailrec
object Day2 {
def splitInstruction(instruction: String): (String, Int) = {
val splitted = instruction.split("\\s")
return (splitted(0), splitted(1).toInt)
}
def calcPosition(instructions: List[(String, Int)]): Int = {
val (horizontal, depth) = calcPositionRec(instructions, 0, 0)
return horizontal * depth
}
@tailrec
def calcPositionRec(instructions: List[(String, Int)], horizontal: Int, depth: Int): (Int, Int) = {
instructions match {
case Nil => (horizontal, depth)
case ("forward", v) :: rest =>
calcPositionRec(rest, horizontal+v, depth)
case ("down", v) :: rest =>
calcPositionRec(rest, horizontal, depth+v)
case ("up", v) :: rest =>
calcPositionRec(rest, horizontal, depth-v)
case _ => (0,0)
}
}
def main(args: Array[String]) = {
val lines = io.readFile(args(0)).map(splitInstruction(_))
val res = calcPosition(lines)
println(res)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment