Skip to content

Instantly share code, notes, and snippets.

@trygvea
Created February 10, 2021 10:52
Show Gist options
  • Save trygvea/a2d9cdbc19ceff3df7eb64ccef3c0597 to your computer and use it in GitHub Desktop.
Save trygvea/a2d9cdbc19ceff3df7eb64ccef3c0597 to your computer and use it in GitHub Desktop.
Kotlin Permutations
package foo
fun <T> permutations(list: List<T>): List<List<T>> = when {
list.size > 10 -> throw Exception("You probably dont have enough memory to keep all those permutations")
list.size <= 1 -> listOf(list)
else ->
permute(list.drop(1)).map { perm ->
(list.indices).map { i ->
perm.subList(0, i) + list.first() + perm.drop(i)
}
}.flatten()
}
package foo
import org.amshove.kluent.shouldBeEqualTo
import org.junit.jupiter.api.Test
class PermutationTest {
@Test
fun `test permutations method`() {
permute(listOf(1, 2, 3)).toSet() shouldBeEqualTo setOf(listOf(1, 2, 3), listOf(1, 3, 2), listOf(2, 1, 3), listOf(2, 3, 1), listOf(3, 1, 2), listOf(3, 2, 1))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment