Created
October 8, 2014 09:24
-
-
Save AhmedSoliman/ce17e5dd4927f4349696 to your computer and use it in GitHub Desktop.
Generate Permutations of String in Scala
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
/** | |
* A question I normally ask in Scala interviews, this is not a tail-recursive implementation | |
*/ | |
object Permutations { | |
def permutations(s: String): List[String] = { | |
def merge(ins: String, c: Char): Seq[String] = | |
for (i <- 0 to ins.length) yield | |
ins.substring(0, i) + c + ins.substring(i, ins.length) | |
if (s.length() == 1) | |
List(s) | |
else | |
permutations(s.substring(0, s.length - 1)).flatMap { p => | |
merge(p, s.charAt(s.length - 1)) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment