Last active
December 2, 2018 13:35
-
-
Save ahoy-jon/7b06cd659b1b199eb2bb21212a74a0e7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def day1(input:Seq[Int]): (Int, Int) = { | |
val part1 = 0 + input.sum | |
val part2 = { | |
val freq: Seq[Int] = Stream.continually(input).flatten | |
val states: Seq[Int] = freq.scanLeft(0)(_ + _) | |
val find: Either[Int, Set[Int]] = foldLeftUntil(states)(Set.empty[Int])( | |
(set, a) => if (set(a)) Left(a) else Right(set + a)) | |
//vu que freq est une steam infinie, c'est correct, | |
// on a soit left, soit un truc qui tourne pour toujours. | |
find.left.get | |
} | |
(part1,part2) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@tailrec | |
def foldLeftUntil[A, B, C](seq: Seq[A])(init: B)(f: (B, A) => Either[C, B]): Either[C, B] = { | |
seq match { | |
case Seq() => Right(init) | |
case Seq(head, tail@_*) => | |
f(init, head) match { | |
case Right(b) => | |
foldLeftUntil(tail)(b)(f) | |
case end => end | |
} | |
} | |
} |
👍 foldLeftUntil
is really missing in std lib.
My impl. is pretty close to your latter solution : it combines both scanLeft
into one
def part2_stream: Iterator[String] => Int = { iter =>
val frequencies = lines
Stream
.continually(frequencies)
.flatten
.scanLeft((0, Set.empty[Int])) {
case ((sum, visited), freq) => (sum + freq, visited + sum)
}
.find { case (sum, visited) => visited.contains(sum)}
.get._1
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ou pas