Created
November 10, 2017 08:17
-
-
Save atonamy/9be29c0991c59edeaf8037d9e1daa41a to your computer and use it in GitHub Desktop.
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
fun main(args : Array<String>) { | |
println("abc".generatePermutations()) | |
} | |
fun StringBuilder.generatePermutations(start: Int = 0, finish: Int = length-1, | |
result: MutableSet<String> = HashSet()) : Set<String> { | |
if(start == finish) | |
result.add(String(this)) | |
else | |
for(i in start .. finish) { | |
swap(start, i) | |
generatePermutations(start+1, finish, result) | |
swap(start, i) | |
} | |
return result | |
} | |
fun StringBuilder.swap(index1: Int, index2: Int) { | |
if(index1 == index2 || index1 < 0 || index2 < 0 || index1 >= length || index2 >= length) | |
return | |
val tmp = this[index1] | |
this[index1] = this[index2] | |
this[index2] = tmp | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment