Advertisement
Guest User

Untitled

a guest
Jun 19th, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.91 KB | None | 0 0
  1. class MovingAverage
  2. attr_accessor :size, :queue
  3. =begin
  4. Initialize your data structure here.
  5. :type size: Integer
  6. =end
  7. def initialize(size)
  8. @size = size
  9. @queue = []
  10. @sum = 0.0
  11. end
  12.  
  13.  
  14. =begin
  15. :type val: Integer
  16. :rtype: Float
  17. =end
  18. def next(val)
  19. if queue.size < size
  20. queue.unshift(val)
  21. # strange that attr_accessor :sum
  22. # does not work
  23. # repl kept complaining about undefined method +
  24. # on nil class for sum += val
  25. # even though p sum.class says it is a Fixnum
  26. @sum += val
  27. else
  28. @sum -= queue.unshift(val).pop
  29. @sum += val
  30. end
  31.  
  32. @sum / queue.size
  33. end
  34. end
  35.  
  36. # Your MovingAverage object will be instantiated and called as such:
  37. # obj = MovingAverage.new(size)
  38. # param_1 = obj.next(val)
  39.  
  40. obj = MovingAverage.new(3)
  41. obj.next(1)
  42. obj.next(3)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement