Created
May 18, 2019 12:31
-
-
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
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
/** | |
* 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