Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy or Java equivalent of sumproduct?

Tags:

groovy

Before I writing my own, does anyone know if Groovy or Java has something pre-built which is similar to Excel's sumproduct function?

The quasi syntax for sumproduct is something like

def list1 = [2,3,4]
def list2 = [5,10,20]

SUMPRODUCT(list1, list2 ...) = 120

You will get 120 ((2*5) + (3*10) + (4*20) = 120)

like image 386
Todd M Avatar asked Dec 24 '22 15:12

Todd M


1 Answers

You can transpose(), collect() and sum the result:

def list1 = [2,3,4]
def list2 = [5,10,20]

assert [list1, list2]
    .transpose()
    .collect { it[0] * it[1] }
    .sum()  == 120
like image 155
Will Avatar answered Jan 03 '23 10:01

Will