1

I trying to calculate a cumulative sum for a list of ints, in imperative style in scala using var and for loop, this seems to be working but I wonder can we do this without using var and counter in a better way?

here is my code

val ar1 = Array[Int](1, 0, 1, 0, 0)            
//> ar1  : Array[Int] = Array(1, 0, 1, 0, 0)
var cumsum = 0.0;                                
//> cumsum  : Double = 0.0
for (i <- 0 until ar1.length) {
  if (i == 0) {
    cumsum = 0;
  } else {
    cumsum = ar1(i - 1) * 0.99 + cumsum;
  }
  println(cumsum)
}   

and here is the output I am expecting

                                          //> 0.0
                                          //| 0.99
                                          //| 0.99
                                          //| 1.98
                                          //| 1.98
Andrey Tyukin
  • 43,673
  • 4
  • 57
  • 93
Masterbuilder
  • 499
  • 2
  • 12
  • 24
  • 2
    Is [this](https://stackoverflow.com/questions/3224935/in-scala-how-do-i-fold-a-list-and-return-the-intermediate-results) sufficient? – Andrey Tyukin Aug 02 '18 at 21:04
  • I tried that, but the output was not what I desired. scanLeft(ar1)(0.0)( _ *0.99+ _ ) //> res0: List[Double] = List(0.0, 1.0, 0.99, 1.9801, 1.960299, 1.94069601) – Masterbuilder Aug 02 '18 at 21:15
  • 1
    The accumulator comes first, the array entry second. `ar1.scanLeft(0.0)(_ + 0.99 * _)` produces `Array(0.0, 0.99, 0.99, 1.98, 1.98, 1.98)` (I don't know what it's supposed to be good for, but here you have it...). – Andrey Tyukin Aug 02 '18 at 21:24
  • cool that works, one more thing why do the result have 6 elements , while our input array has only 5 elements. – Masterbuilder Aug 02 '18 at 21:34
  • The first 0.0 is included. If you `ar1.scanLeft(42.0)(...)`, then the first `42.0` will be included. That's because `blah.scanLeft(x)(y).last == blah.foldLeft(x)(y)`. – Andrey Tyukin Aug 02 '18 at 21:35
  • 0.0 at first place is desired as there is no previous data exist, I feel the last 1.98 doesn't make sense because it is going beyond the current index. – Masterbuilder Aug 02 '18 at 21:42
  • It does make sense. If `Array(42.0).scanLeft(0.0)(_ + 0.99 * _)` returned `Array(0.0)`, this, indeed, wouldn't make any sense whatsoever. Just drop the element that you don't need. – Andrey Tyukin Aug 02 '18 at 21:48

0 Answers0