Created
April 14, 2016 03:34
-
-
Save izmailoff/dbc7bdc03154f1c969e4fae5773e7135 to your computer and use it in GitHub Desktop.
Implementation of permutations in Scala (functional, recursive, lazy)
This file contains hidden or 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
object Perms extends App { | |
def perms[T](xs: List[T]): Stream[List[T]] = | |
xs match { | |
case Nil => Stream.empty | |
case single@List(e) => Stream(single) | |
case l => | |
val s = for { | |
i <- (0 until l.length).toStream | |
(pref, suf) = l.splitAt(i) | |
} yield (suf.head, pref ::: suf.tail) | |
s.flatMap { case (e, rem) => perms(rem).map(ys => e :: ys) } | |
} | |
val testData = (1 to 5).toList | |
val isMyImplSubsetOfRefImpl = (perms(testData).toSet -- testData.permutations.toStream).size == 0 | |
val isRefImplSubsetOfMyImpl = (testData.permutations.toSet -- perms(testData)).size == 0 | |
val isCorrect = isMyImplSubsetOfRefImpl && isRefImplSubsetOfMyImpl | |
println(s"Matches library implementation results?: $isCorrect") | |
val l = (1 to 1000).toList | |
println("First 10 results of a very large stream (n = 1000):") | |
perms(l) take 10 foreach println | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Prints: