Calculating the Moving Average of a List

后端 未结 18 1177
悲哀的现实
悲哀的现实 2020-12-07 09:01

This weekend I decided to try my hand at some Scala and Clojure. I\'m proficient with object oriented programming, and so Scala was easy to pick up as a language, but wante

18条回答
  •  醉酒成梦
    2020-12-07 09:41

    Being late on the party, and new to functional programming too, I came to this solution with an inner function:

    def slidingAvg (ixs: List [Double], len: Int) = {
        val dxs = ixs.map (_ / len) 
        val start = (0.0 /: dxs.take (len)) (_ + _)
        val head = List.make (len - 1, 0.0)
    
        def addAndSub (sofar: Double, from: Int, to: Int) : List [Double] =  
            if (to >= dxs.length) Nil else {
                val current = sofar - dxs (from) + dxs (to) 
                current :: addAndSub (current, from + 1, to + 1) 
            }
    
        head ::: start :: addAndSub (start, 0, len)
    }
    
    val xs = List(2, 4, 7, 6, 3, 8, 12, 9, 4, 1)
    slidingAvg (xs.map (1.0 * _), 4)
    

    I adopted the idea, to divide the whole list by the period (len) in advance. Then I generate the sum to start with for the len-first-elements. And I generate the first, invalid elements (0.0, 0.0, ...) .

    Then I recursively substract the first and add the last value. In the end I listify the whole thing.

提交回复
热议问题