Skip to content

Instantly share code, notes, and snippets.

@matteo-grella
Created May 18, 2019 12:31
Show Gist options
  • Save matteo-grella/3d431e64d1691f67562350d0f94bfd22 to your computer and use it in GitHub Desktop.
Save matteo-grella/3d431e64d1691f67562350d0f94bfd22 to your computer and use it in GitHub Desktop.
Extension method that returns the combinations of the elements of a list
/**
* Returns the combinations of the elements in this list as a list of pairs.
*
* The returned list is empty if this collection contains less than two elements.
*
* @return the combinations of the elements
*/
fun <E>List<E>.combine(): List<Pair<E, E>> = this.foldIndexed(mutableListOf()) { i, acc, element ->
for (j in i + 1 until this.size) {
acc.add(Pair(element, this[j]))
}
acc
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment