Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pair items in a list with one another in Kotlin

Tags:

kotlin

I want to pair items in a list with one another

Example

list("A","B","C") to -> list(Pair(A,B),Pair(A,C),Pair(B,C))

list("A","B","C","D") to -> list(Pair(A,B),Pair(A,C),Pair(A,D),Pair(B,C),Pair(B,D),Pair(C,D))

I have tried using zipWithNext, but it does not help my cause. If anyone can show me how I can achieve this?

like image 864
Hussain Avatar asked Nov 02 '25 22:11

Hussain


1 Answers

You can simply nest for loops and use ranges for that:

fun permute(list: List<String>): List<Pair<String, String>> {
    var result: MutableList<Pair<String, String>> = mutableListOf()

    for (i in 0..(list.size - 1)) {
        val s = list.get(i)

        for (j in (i + 1)..(list.size - 1)) {
            val p = Pair(s, list.get(j))
            result.add(p)
        }
    }

    return result
}

There might be ways that are more Kotlin style, but I don't know one at the moment...

Using this method in a fun main() like this

fun main() {
    val list = listOf("A", "B", "C", "D")

    println(permute(list))
}

will output

[(A, B), (A, C), (A, D), (B, C), (B, D), (C, D)]
like image 148
deHaar Avatar answered Nov 04 '25 18:11

deHaar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!