Day 1
This commit is contained in:
parent
92536fb426
commit
808cf54faf
45
Day1.scala
Normal file
45
Day1.scala
Normal file
|
@ -0,0 +1,45 @@
|
||||||
|
// 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)
|
1000
day1.input
Normal file
1000
day1.input
Normal file
File diff suppressed because it is too large
Load diff
Loading…
Reference in a new issue