Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Product of a List or Array in Kotlin

Tags:

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
like image 230
Andre Breton Avatar asked Aug 25 '17 19:08

Andre Breton


2 Answers

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

like image 108
uzilan Avatar answered Sep 20 '22 04:09

uzilan


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
like image 26
Bob Avatar answered Sep 18 '22 04:09

Bob