Skip to content

Instantly share code, notes, and snippets.

@nbardiuk
Last active February 3, 2020 17:18
Show Gist options
  • Save nbardiuk/ec16046263734c795a82d33dcf83fb81 to your computer and use it in GitHub Desktop.
Save nbardiuk/ec16046263734c795a82d33dcf83fb81 to your computer and use it in GitHub Desktop.
Moving avarage
(defn- slide [window x]
(-> window (subvec 1) (conj x)))
(defn- windows [n xs]
(let [first-window (vec (take n xs))
the-rest (drop n xs)]
(when (and (< 0 n) (= n (count first-window)))
(reductions slide first-window the-rest))))
(defn- avarage [xs]
(/ (apply + xs) (count xs)))
(defn moving-avarage [n xs]
(->> xs (windows n) (map avarage)))
(moving-avarage 1 []) ; => ()
(moving-avarage -1 [1 2 3 4]) ; => ()
(moving-avarage 0 [1 2 3 4]) ; => ()
(moving-avarage 1 [1 2 3 4]) ; => (1 2 3 4)
(moving-avarage 2 [1 2 3 4]) ; => (3/2 5/2 7/2)
(moving-avarage 3 [1 2 3 4]) ; => (2 3)
(moving-avarage 4 [1 2 3 4]) ; => (5/2)
(moving-avarage 5 [1 2 3 4]) ; => ()
(nth (moving-avarage 3 (range)) 1000000) ; => 1000001
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment