Skip to content

Instantly share code, notes, and snippets.

@ahoy-jon
Last active December 2, 2018 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahoy-jon/7b06cd659b1b199eb2bb21212a74a0e7 to your computer and use it in GitHub Desktop.
Save ahoy-jon/7b06cd659b1b199eb2bb21212a74a0e7 to your computer and use it in GitHub Desktop.
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)
}
@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
}
}
}
@ahoy-jon
Copy link
Author

ahoy-jon commented Dec 2, 2018

ou pas

scala
val part2 = {
    val freq: Seq[Int] = Stream.continually(input).flatten

    val states: Seq[Int] = freq.scanLeft(0)(_ + _)
    
    val foundStates: Seq[Set[Int]] = states.scanLeft(Set.empty[Int])(_ + _)
    
    states.zip(foundStates).find({case (s,fs) => fs(s)}).get._1
  }

@YannMoisan
Copy link

👍 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