Ariane Breton
Ariane Breton

Reputation: 1333

Product of a List or Array in Kotlin

I'm trying to find a way to get the product of a List or Array without using "repeat" or any loop on Kotlin but after some research I couldn't find anything similar.

Something like this in Python would be:

>>> reduce(lambda x, y: x*y, [1,2,3,4,5,6])
output: 720

Upvotes: 18

Views: 10288

Answers (5)

Anowar Hossain Anu
Anowar Hossain Anu

Reputation: 11

Use the fold or reduce function. Both will work.

    val array = arrayOf(1, 2, 3, 4, 5, 6)
    println("Product of list: ${listOfMultiplication(array)}")
    fun listOfMultiplication(array: Array<Int>): Int {
        return array.reduce { total, next ->  total * next }
    }
    val array = arrayOf(1, 2, 3, 4, 5, 6)
    println("Product of list: ${listOfMultiplication(array)}")
    fun listOfMultiplication(array: Array<Int>): Int {
        return array.fold(1) { total, next -> total * next }
    }

Upvotes: 0

uzilan
uzilan

Reputation: 2624

An even simpler solution might be: (1..6).reduce(Int::times)

Upvotes: 23

HyunJin
HyunJin

Reputation: 336

Hope this helps:

fun main(args: Array<String>){
   val array = intArrayOf(1, 2, 3, 4, 5, 6)
   val product = array.fold(1){acc, i -> acc * i}
   println("The result is: $product")
}

This will output the product of the array.

Upvotes: 2

Rafal G.
Rafal G.

Reputation: 4432

Use the fold function

val total = listOf(1, 2, 3, 4, 5).fold(1, { total, next -> total * next })

Upvotes: 8

Bob
Bob

Reputation: 13865

You can use reduce in Kotlin.

From the doc:

Accumulates value starting with the first element and applying operation from left to right to current accumulator value and each element.

val list = listOf<Int>(1, 2, 3, 4, 5, 6)

val array = intArrayOf(1, 2, 3, 4, 5, 6)

list.reduce { acc, i ->  acc * i }  // returns 720

array.reduce { acc, i -> acc * i }  // returns 720

Upvotes: 21

Related Questions