Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala: Calculating the Moving Sum of a List with a fixed window

I am new to Scala and I want to calculate a moving sum with a fixed window for a list.

For example: Given the list values (1.0, 2.0, 3.0, 6.0, 7.0, 8.0, 12.0, 9.0, 4.0, 1.0), and the period 4, the function should return: (1.0, 3.0, 6.0, 12.0, 18.0, 24.0, 33.0, 36.0, 33.0, 26.0)

If list.size < period then just return cumulative sum.

I have made some attempts

def mavg(values: List[Double], period: Int): List[Double] = {
  if (values.size <= period) (values.sum ) :: List.fill(period -1)(values.sum ) else {
      val rest: List[Double] = mavg(values.tail, period)
      (rest.head + ((values.head - values(period)))):: rest
  }
}

However, I got

List(12.0, 18.0, 24.0, 33.0, 36.0, 33.0, 26.0, 26.0, 26.0, 26.0

which is not correct. I dont want to use Pyspark to get the results. Can someone help?

Many thanks.

like image 423
FlyUFalcon Avatar asked Apr 29 '20 21:04

FlyUFalcon


1 Answers

  def mavg(values: Seq[Double], period: Int): Seq[Double] = {
    (Seq.fill(math.min(period - 1, values.length))(0.0) ++ values) // padding zeros
      .sliding(period)                  
      .map(_.sum)
      .toSeq
  }
like image 154
User9123 Avatar answered Jan 27 '23 15:01

User9123