Dmitrii Dmitrii - 17 days ago 4x
Scala Question

Multiply elements of list of lists with each other

I have List of lists

List[List[Int] to n]
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]


You can do it using foldLeft this way:

list.foldLeft(List(1)) {
  case (acc, item) => acc.flatMap(v =>*v))


Lets define method producing all possible multiplication of pairs of two lists:

def mul(a:List[Int], b:List[Int]) = b.flatMap (item =>*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)