Skip to content

Instantly share code, notes, and snippets.

@daviscale
Created April 29, 2021 00:31
Show Gist options
  • Save daviscale/0879d474ccaaba6baaf933ddb3708578 to your computer and use it in GitHub Desktop.
Save daviscale/0879d474ccaaba6baaf933ddb3708578 to your computer and use it in GitHub Desktop.
def makeNextSequence(
previousSeq: List[Int],
currentSubSeq: List[Int] = List.empty,
accumulatedSeq: List[List[Int]] = List.empty
): List[Int] = {
previousSeq match {
case head :: tail if currentSubSeq.isEmpty =>
makeNextSequence(tail, List(head), accumulatedSeq)
case head :: tail if head != currentSubSeq.head =>
makeNextSequence(tail, List(head), accumulatedSeq :+ currentSubSeq)
case head :: tail if head == currentSubSeq.head =>
makeNextSequence(tail, currentSubSeq :+ head, accumulatedSeq)
case Nil =>
val finalAccumulated = accumulatedSeq :+ currentSubSeq
val nextSeq = finalAccumulated flatMap { subSeq =>
List(subSeq.size, subSeq.head)
}
println(nextSeq.mkString(" "))
nextSeq
}
}
@daviscale
Copy link
Author

Here's this function in action on the Scala console:

scala> (1 to 10).foldLeft(List(1)) { case (result, _) => makeNextSequence(result) }
1 1
2 1
1 2 1 1
1 1 1 2 2 1
3 1 2 2 1 1
1 3 1 1 2 2 2 1
1 1 1 3 2 1 3 2 1 1
3 1 1 3 1 2 1 1 1 3 1 2 2 1
1 3 2 1 1 3 1 1 1 2 3 1 1 3 1 1 2 2 1 1
1 1 1 3 1 2 2 1 1 3 3 1 1 2 1 3 2 1 1 3 2 1 2 2 2 1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment