Skip to content

Commit f3a6a70

Browse files
committed
permutationsOf() yields all possible permutations of the given list elements
1 parent 06a1836 commit f3a6a70

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

src/main/kotlin/de/ronny_h/aoc/extensions/Combinations.kt

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,18 @@ fun <A, B> combinationsOf(first: List<A>, second: List<B>) = sequence {
2424
}
2525
}
2626
}
27+
28+
/**
29+
* @return A sequence of lists containing all permutations of the original one.
30+
*/
31+
fun <E> permutationsOf(list: List<E>): Sequence<List<E>> = sequence {
32+
if (list.isEmpty()) {
33+
yield(emptyList())
34+
}
35+
36+
for (i in list.indices) {
37+
permutationsOf(list - list[i]).forEach { smallerPermutation ->
38+
yield(smallerPermutation + list[i])
39+
}
40+
}
41+
}

src/test/kotlin/de/ronny_h/aoc/extensions/CombinationsTest.kt

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
package de.ronny_h.aoc.extensions
22

33
import io.kotest.core.spec.style.StringSpec
4+
import io.kotest.data.blocking.forAll
5+
import io.kotest.data.row
6+
import io.kotest.matchers.collections.shouldContainExactlyInAnyOrder
47
import io.kotest.matchers.shouldBe
58

69
class CombinationsTest : StringSpec({
@@ -58,4 +61,25 @@ class CombinationsTest : StringSpec({
5861
2 to "b",
5962
)
6063
}
64+
65+
"permutationsOf() yields all possible permutations of the given list elements" {
66+
forAll(
67+
row(emptyList(), listOf(emptyList())),
68+
row(listOf(1), listOf(listOf(1))),
69+
row(listOf(1, 2), listOf(listOf(1, 2), listOf(2, 1))),
70+
row(
71+
listOf(1, 2, 3),
72+
listOf(
73+
listOf(1, 2, 3),
74+
listOf(1, 3, 2),
75+
listOf(2, 1, 3),
76+
listOf(2, 3, 1),
77+
listOf(3, 1, 2),
78+
listOf(3, 2, 1)
79+
)
80+
),
81+
) { input, permutations ->
82+
permutationsOf(input).toList() shouldContainExactlyInAnyOrder permutations
83+
}
84+
}
6185
})

0 commit comments

Comments
 (0)