-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathGeneratePermutations.kt
72 lines (62 loc) · 1.57 KB
/
GeneratePermutations.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package handbook
import utils.shouldBe
import utils.shouldBeOneOf
/**
* Given array of integers, generate its permutations.
*/
private class GeneratePermutations(val nums: IntArray) : () -> List<List<Int>> {
val result = mutableListOf<List<Int>>()
override fun invoke(): List<List<Int>> {
permutation(0, nums.lastIndex)
return result
}
private fun permutation(low: Int, high: Int) {
if (low == high) {
result.add(nums.toList())
}
for (i in low..high) {
swap(nums, low, i)
permutation(low + 1, high)
swap(nums, low, i)
}
}
private fun swap(array: IntArray, i: Int, j: Int) {
val temp = array[i]
array[i] = array[j]
array[j] = temp
}
}
fun main() {
run {
val expected = listOf(
listOf(0, 1, 2),
listOf(0, 2, 1),
listOf(1, 0, 2),
listOf(1, 2, 0),
listOf(2, 0, 1),
listOf(2, 1, 0)
)
GeneratePermutations(intArrayOf(0, 1, 2))
.invoke()
.also {
it.size shouldBe expected.size
}
.forEach {
it shouldBeOneOf expected
}
}
run {
val expected = listOf(
listOf(0, 1),
listOf(1, 0)
)
GeneratePermutations(intArrayOf(0, 1))
.invoke()
.also {
it.size shouldBe expected.size
}
.forEach {
it shouldBeOneOf expected
}
}
}