Created
February 24, 2014 19:24
-
-
Save MikeInnes/9195081 to your computer and use it in GitHub Desktop.
This file contains 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
function rand_first_index(n, k) | |
r = rand() | |
p = k/n | |
i = 1 | |
while p < r | |
i += 1 | |
p += (1-p)k/(n-(i-1)) | |
end | |
return i | |
end | |
function ordered_sample_norep!(xs::AbstractArray, target::AbstractArray) | |
n = length(xs) | |
k = length(target) | |
i = 0 | |
for j in 1:k | |
step = rand_first_index(n, k) | |
n -= step | |
i += step | |
target[j] = xs[i] | |
k -= 1 | |
end | |
return target | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment