aoc2023/Common.scala

32 lines
921 B
Scala
Raw Normal View History

2023-12-03 15:50:17 +00:00
//> using dep org.scala-lang.modules::scala-parser-combinators::2.3.0
2023-12-02 14:31:39 +00:00
package aoc
2023-12-03 15:50:17 +00:00
import scala.util.parsing.combinator._
2023-12-02 14:31:39 +00:00
def iterate[T](get: => T | Null) =
Iterator.continually(get).takeWhile(_ != null).map(_.nn)
def lines = iterate(scala.io.StdIn.readLine())
2023-12-03 15:50:17 +00:00
class CommonParser extends RegexParsers:
2023-12-09 12:20:50 +00:00
val num = """-?(0|[1-9]\d*)""".r ^^ { _.toInt }
val long = """-?(0|[1-9]\d*)""".r ^^ { _.toLong }
2023-12-03 15:50:17 +00:00
object CommonParser extends CommonParser
2023-12-10 15:32:46 +00:00
extension [T](ss: Seq[T])
@scala.annotation.tailrec
def findMap[U](f: T => Option[U]): Option[U] =
if ss.isEmpty then None
else
val (head, tail) = (ss.head, ss.tail)
f(head) match
case None => tail.findMap(f)
case v @ Some(_) => v
2023-12-13 14:25:46 +00:00
def splitBy(cond: T => Boolean): Seq[Seq[T]] =
val splitPos = ss.indexWhere(cond)
if splitPos == -1 then Seq(ss)
else ss.take(splitPos) +: ss.drop(splitPos + 1).splitBy(cond)