advent-of-code/2018/Scala/1.scala

31 lines
862 B
Scala
Raw Normal View History

2019-11-27 02:33:22 +01:00
import scala.collection.mutable
import scala.io.Source
import scala.collection.immutable.LazyList.#::
val lines = Source.fromFile(getClass.getResource("/file.txt").getFile).getLines().toList
// Solution 1
val result1 = lines.foldLeft (0) { (acc, i) => acc + Integer.parseInt(i) }
println(result1)
// Solution 2
def toLazyLoop[A](list: List[A]): LazyList[A] = {
def toLazy[A](list: List[A]): LazyList[A] = {
list match {
case List() => LazyList()
case h::t => h #:: toLazy(t)
}
}
toLazy(list) #::: toLazyLoop(list)
}
2019-11-27 02:36:20 +01:00
val hash = new mutable.HashSet[Int]()
def findFirstRepeat[A](lazylist:LazyList[String], acc:Int):Int =
2019-11-27 02:33:22 +01:00
if (!hash.add(acc)) acc
else lazylist match {
2019-11-27 02:36:20 +01:00
case hd #:: tl => findFirstRepeat(tl, (acc + hd.toInt))
2019-11-27 02:33:22 +01:00
}
2019-11-27 02:36:20 +01:00
val result2 = findFirstRepeat(toLazyLoop(lines), 0)
2019-11-27 02:33:22 +01:00
println("First repeat frequency: " + result2)