Last active
January 7, 2017 20:34
-
-
Save orisano/29970fa59e60e5dcb4fad3f09ee3093c to your computer and use it in GitHub Desktop.
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
def array_sample(arr, k) | |
rng = Random.new | |
sample = Array.new k | |
sample[0] = arr[0] | |
(1...k).each {|i| | |
r = rng.rand(i + 1) | |
sample[i] = sample[r] | |
sample[r] = arr[i] | |
} | |
(k...arr.size).each {|i| | |
r = rng.rand(i + 1) | |
sample[r] = arr[i] if r < k | |
} | |
sample | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
O(min(arr.size, n)) かもしれないやつ