Last active
September 22, 2018 10:34
-
-
Save kakajika/f9a3012b928c2012365c07363ec4b3fe to your computer and use it in GitHub Desktop.
List all combinations of picking n elements.
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
fun <T> Collection<T>.combinations(n: Int): List<List<T>> { | |
return when { | |
n < 0 -> throw Error("combinations size cannot be negative") | |
n > size -> emptyList() | |
n == 1 -> map { mutableListOf(it) } | |
else -> foldIndexed<T, List<List<T>>>(mutableListOf()) { index, all, first -> | |
all + drop(index + 1) | |
.combinations(n - 1) | |
.map { it + first } | |
} | |
} | |
} | |
val list = listOf(1, 2, 3, 4) | |
list.combinations(2) // => [[2, 1], [3, 1], [4, 1], [3, 2], [4, 2], [4, 3]] | |
list.combinations(3) // => [[3, 2, 1], [4, 2, 1], [4, 3, 1], [4, 3, 2]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment