Skip to content

Instantly share code, notes, and snippets.

@kakajika
Last active September 22, 2018 10:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kakajika/f9a3012b928c2012365c07363ec4b3fe to your computer and use it in GitHub Desktop.
Save kakajika/f9a3012b928c2012365c07363ec4b3fe to your computer and use it in GitHub Desktop.
List all combinations of picking n elements.
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