Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class MovingAverage
- attr_accessor :size, :queue
- =begin
- Initialize your data structure here.
- :type size: Integer
- =end
- def initialize(size)
- @size = size
- @queue = []
- @sum = 0.0
- end
- =begin
- :type val: Integer
- :rtype: Float
- =end
- def next(val)
- if queue.size < size
- queue.unshift(val)
- # strange that attr_accessor :sum
- # does not work
- # repl kept complaining about undefined method +
- # on nil class for sum += val
- # even though p sum.class says it is a Fixnum
- @sum += val
- else
- @sum -= queue.unshift(val).pop
- @sum += val
- end
- @sum / queue.size
- end
- end
- # Your MovingAverage object will be instantiated and called as such:
- # obj = MovingAverage.new(size)
- # param_1 = obj.next(val)
- obj = MovingAverage.new(3)
- obj.next(1)
- obj.next(3)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement