aoc2023/Day1.scala

46 lines
1.4 KiB
Scala
Raw Normal View History

2023-12-01 15:01:45 +00:00
// Part 1
def literalDigits(s: String) =
s.toSeq.filter(_.isDigit).map(v => (v - '0').toInt)
def getValue(toDigits: String => Seq[Int])(s: String): Int =
val digits = toDigits(s)
digits.head * 10 + digits.last
def iterate[T](get: => T | Null) = new scala.collection.IterableOnce[T]:
override def iterator = new Iterator[T]:
var item: Option[T | Null] = None
override def hasNext: Boolean =
if item.isEmpty then item = Some(get)
item.get != null
override def next(): T =
val r = item.get.nn
item = None
r
def getSum(toDigits: String => Seq[Int]) =
val values =
Seq.from(iterate(scala.io.StdIn.readLine())).map(getValue(toDigits))
println(values.sum)
// Part 2
val englishDigits =
Seq("one", "two", "three", "four", "five", "six", "seven", "eight", "nine")
def literalOrEnglishDigits(s: String) =
@scala.annotation.tailrec
def loop(idx: Int, accum: Seq[Int]): Seq[Int] =
if idx < 0 then accum
else if s(idx).isDigit then loop(idx - 1, (s(idx) - '0').toInt +: accum)
else
val toMatch = s.slice(idx, idx + 5 /* enough to match english */ )
val digit = englishDigits.indexWhere(toMatch.startsWith _)
val nAccum = if digit == -1 then accum else (digit + 1) +: accum
loop(idx - 1, nAccum)
loop(s.length() - 1, Seq.empty)
@main def Run(part: Int) = part match
case 1 => getSum(literalDigits)
case 2 => getSum(literalOrEnglishDigits)