Reputation: 624
I have List of lists List[List[Int] to n]
and Lists[Int]
are of different size and i want to multiply values all of them between each other.
For List(List(1,2,3), List(4,5), List(6)) it would be
1*4*6, 1*5*6, 2*4*6, 2*5*6, 3*4*6, 3*5*6
and so on and return result as a List of resulting values List[24, 30, 48, 60, 72, 90]
Upvotes: 1
Views: 1915
Reputation: 8866
You can do it using foldLeft this way:
list.foldLeft(List(1)) {
case (acc, item) => acc.flatMap(v => item.map(_*v))
}
Explanation
Lets define method producing all possible multiplication of pairs of two lists:
def mul(a:List[Int], b:List[Int]) = b.flatMap (item => a.map(_*item))
this method for each item in b produces a list of items from a multiplied by current value of b
Now we can apply this procedure to all elements of list of lists, giving it initial value of List(1)
Upvotes: 4