Created
January 26, 2013 08:54
-
-
Save vkostyukov/4641155 to your computer and use it in GitHub Desktop.
Puzzle Example from CCI.
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
object Permutation extends App { | |
def generate(s: String): Array[String] = s.length() match { | |
case 1 => Array(s) | |
case 2 => Array("" + s(0) + s(1), "" + s(1) + s(0)) | |
case _ => | |
val first = s.head | |
var perms = generate(s.tail) | |
var result: Array[String] = Array.fill(perms.length * (perms(0).length() + 1)) { "" } | |
var offset = 0 | |
perms foreach { p => | |
for (i <- 0 to p.length()) { | |
result(offset) += p.substring(0, i) | |
result(offset) += first | |
result(offset) += p.substring(i, p.length()) | |
offset += 1 | |
} | |
} | |
result | |
} | |
assert { generate("abc").corresponds(Array("abc", "bac", "bca", "acb", "cab", "cba")) { _ == _ } } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment