Home > OS >  Is there an easy way to multiply each element with each other in array / list - Kotlin?
Is there an easy way to multiply each element with each other in array / list - Kotlin?

Time:07-15

I have got {1,2,3} / or it might be a list<Int> is there an easy way to multiply each element with each other like 1*2 , 1*3, 2*3 ?

CodePudding user response:

This should work, given that you probably don't want to include the duplicates like items[i] * items[j] and items[j] * items[i]

val items = listOf(1, 2, 3, 4)

val result = items.flatMapIndexed { index, a -> 
    items.subList(index   1, items.size).map { b -> a * b }
}

println(result) // [2, 3, 4, 6, 8, 12]
  • flatMapIndexed builds a list for each of the items elements by evaluating the lambda on the index and the item, and then concatenates the lists.
  • subList is an efficient way to take the items in the specific range: starting at the next index, and until the end of the list.

CodePudding user response:

You can try the old-fashioned way: nested loops

fun main(args: Array<String>) {
    val list = listOf( 1, 2, 3 )
    
    for (i in list.indices) {
        for (j in (i   1) until list.size) {
            println("${list[i]} * ${list[j]} = ${list[i] * list[j]}")
        }
    }
}

Output of this code:

1 * 2 = 2
1 * 3 = 3
2 * 3 = 6

CodePudding user response:

If you did want all the permutations (every possible ordering), you could do something like this:

val result = with(items) {
    flatMapIndexed { i, first ->
        slice(indices - i).map { second -> // combine first and second here }
    }
}

slice lets you provide a list of indices for the elements you want to pull, so you can easily exclude the current index and get all the other elements to combo it with. Takes an IntRange too, so you can do slice(i 1 until size) to get the combination (every pairing) functionality too.

Not as efficient as hotkey's subList version (since that doesn't make a copy) but you can get two behaviours this way so I thought I'd mention it! But if I were making a reusable function rather than a quick one-liner, I'd probably go with deHaar's approach with the nested for loops, it's efficient and easy enough to tweak for either behaviour

  • Related