Created
February 10, 2021 10:52
-
-
Save trygvea/a2d9cdbc19ceff3df7eb64ccef3c0597 to your computer and use it in GitHub Desktop.
Kotlin Permutations
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
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() | |
} |
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
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