Last active
January 1, 2025 08:16
-
-
Save rrguntaka/58f5fe07272d1858f0cd45709543ea0d to your computer and use it in GitHub Desktop.
Pairs from list python and Kotlin (Java)
This file contains hidden or 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
/** | |
* Generates all possible unique pairs of elements from the input list. | |
* @param items Input list of elements | |
* @return Pairs containing all possible combinations | |
* @throws IllegalArgumentException if the input list is null | |
*/ | |
fun <T> combs(items: List<T>): List<Pair<T, T>> { | |
require(items.isNotEmpty()) { "Input list cannot be empty" } | |
return items.flatMapIndexed { index, item -> | |
items.drop(index + 1).map { item to it } | |
} | |
} | |
//Sample usage | |
combs(listOf(1, 2, 3, 4, 5)).forEach { println(it) } |
This file contains hidden or 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
def _comb_pairs(h, t): | |
for e in t: yield h, e | |
if len(t) > 1: yield from _comb_pairs(t[0], t[1:]) | |
def comb_pairs(l): yield from _comb_pairs(l[0], l[1:]) | |
# Sample usage | |
for i in comb_pairs((1, 2, 3, 4, 5)): print(i) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment