Created
July 27, 2018 20:00
-
-
Save Akeboshiwind/4dc8be77cbdd01426072f410e35bbf92 to your computer and use it in GitHub Desktop.
An implementation of the reservoir sampling algorithm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; Todo: write as a transducer | |
(defn reservoir-sample | |
"Uniformly choose a sample of k elements from lst" | |
[k lst] | |
(first | |
(reduce | |
(fn [[sample length] next] | |
(let [r (rand-int length)] | |
[(if (< r k) | |
(assoc sample r next) | |
sample) | |
(inc length)])) | |
[(vec (take k lst)) k] | |
(drop k lst)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Chooses a sample of k elements uniformly all with constant space requirements and a linear time complexity.