Skip to content

Instantly share code, notes, and snippets.

@grig
Created May 9, 2010 00:34
Show Gist options
  • Save grig/394854 to your computer and use it in GitHub Desktop.
Save grig/394854 to your computer and use it in GitHub Desktop.
require 'active_support' # Array#sum
def avg(a)
a.sum.to_f/a.size
end
def groups(a, k)
result = []
while (a.size >= k)
result << a[0..k-1]
a.shift
end
result
end
def moving_average(src, k)
groups(src, k).map do |win|
avg(win)
end
end
# moving_average([1,2,3,4,5,6], 3) => [2.0, 3.0, 4.0, 5.0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment