-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathPermutation.kt
42 lines (36 loc) · 1.08 KB
/
Permutation.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package algorithmdesignmanualbook.heuristics.backtrack
import utils.assertIterableSameInAnyOrder
class Permutation(val str: String) {
val result = mutableListOf<String>()
fun execute(): List<String> {
if (str.isEmpty()) {
result.add("")
return result
}
permutation(str, "")
return result
}
private fun permutation(current: String, prefix: String) {
if (current.isEmpty()) {
result.add(prefix)
}
for (i in 0..current.lastIndex) {
val remainder = current.substring(0, i) + current.substring(i + 1)
permutation(remainder, prefix + current[i])
}
}
}
fun main() {
assertIterableSameInAnyOrder(
actual = Permutation("").execute(),
expected = listOf("")
)
assertIterableSameInAnyOrder(
actual = Permutation("abc").execute(),
expected = listOf("abc", "acb", "bac", "bca", "cab", "cba")
)
assertIterableSameInAnyOrder(
actual = Permutation("ab").execute(),
expected = listOf("ab", "ba")
)
}