Day 03
This commit is contained in:
parent
8411bfbc15
commit
64ce0c862d
2 changed files with 61 additions and 0 deletions
55
src/day03.scala
Normal file
55
src/day03.scala
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
package aoc
|
||||
package day03
|
||||
|
||||
import scala.annotation.tailrec
|
||||
|
||||
val dayNumber = "03"
|
||||
|
||||
@main def part1: Unit =
|
||||
println(part1(loadInput(dayNumber)))
|
||||
|
||||
@main def part2: Unit =
|
||||
println(part2(loadInput(dayNumber)))
|
||||
|
||||
def part1(input: String): String =
|
||||
@tailrec def parseMul(s: String, instructions: List[Int]): List[Int] =
|
||||
s match
|
||||
case s"mul($l,$r)$rest"
|
||||
if l.trim.forall(_.isDigit) && r.trim.forall(_.isDigit) =>
|
||||
parseMul(rest, (l.trim.toInt * r.trim.toInt) :: instructions)
|
||||
case "" => instructions
|
||||
case _ => parseMul(s.drop(1), instructions)
|
||||
|
||||
parseMul(input, Nil).sum.toString
|
||||
|
||||
def part2(input: String): String =
|
||||
enum Instruction:
|
||||
case Mul(l: Int, r: Int)
|
||||
case Do
|
||||
case Dont
|
||||
import Instruction.*
|
||||
|
||||
@tailrec def parseInstructions(
|
||||
s: String,
|
||||
instructions: List[Instruction]
|
||||
): List[Instruction] =
|
||||
s match
|
||||
case s"mul($l,$r)$rest"
|
||||
if l.trim.forall(_.isDigit) && r.trim.forall(_.isDigit) =>
|
||||
parseInstructions(rest, Mul(l.trim.toInt, r.trim.toInt) :: instructions)
|
||||
case s"do()$rest" => parseInstructions(rest, Do :: instructions)
|
||||
case s"don't()$rest" => parseInstructions(rest, Dont :: instructions)
|
||||
case "" => instructions
|
||||
case _ => parseInstructions(s.drop(1), instructions)
|
||||
|
||||
parseInstructions(input, Nil)
|
||||
.foldRight((0, false)) { case (inst, (sum, ignoreNext)) =>
|
||||
inst match
|
||||
case Mul(l, r) =>
|
||||
if ignoreNext then (sum, ignoreNext)
|
||||
else (sum + l * r, ignoreNext)
|
||||
case Do => (sum, false)
|
||||
case Dont => (sum, true)
|
||||
}
|
||||
._1
|
||||
.toString
|
||||
Loading…
Add table
Add a link
Reference in a new issue