Skip to content

Instantly share code, notes, and snippets.

@AhmedSoliman
Created October 8, 2014 09:24
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save AhmedSoliman/ce17e5dd4927f4349696 to your computer and use it in GitHub Desktop.
Save AhmedSoliman/ce17e5dd4927f4349696 to your computer and use it in GitHub Desktop.
Generate Permutations of String in Scala
/**
* 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