Scala partial sum with current and all past items in the list

We have a list of integers: [1,4,5,6,6,7,9] .

The idea is to generate a list with the same length and sum up to the current element of the type: [1,5,10,16,22,29,38] .

In the Java world, it will look like this:

 int sum = 0; int[] table = {1,4,5,6,6,7,9} int[] res = new int[table.length] for(int i=0; i<table.length; i++) { sum += table[i] res[i] = sum } 

I know that there are more elegant and effective solutions. My question is: how to do something like this in Scala in a more efficient way?

thanks!

+5
source share
2 answers

You are looking for a scan combinator.

 List(1,4,5,6,6,7,9).scanLeft(0)(_ + _) res1: List[Int] = List(0, 1, 5, 10, 16, 22, 29, 38) 

Delete the leading element with the tail, if you want, I am not aware of the scan version that does not accept the initial value. The complexity is O (n) for this guy, and you can implement it yourself by folding the list using the battery and the list (which contains past batteries). The last you take as a result.

+5
source

The answer to @uberwatch is correct, but for completeness here a more β€œgeneral" functional solution uses foldLeft :

 val xs = Vector(1,4,5,6,6,7,9) val (sumList, sum) = xs.foldLeft((Vector.empty[Int], 0)) { case ((list, total), x) => val newTotal = x + total (list :+ newTotal, newTotal) } // sumList: Vector(1, 5, 10, 16, 22, 29, 38) // sum: Int = 38 
+2
source

Source: https://habr.com/ru/post/1215976/


All Articles