Skip to content

Instantly share code, notes, and snippets.

@orisano
Last active January 7, 2017 20:34
Show Gist options
  • Save orisano/29970fa59e60e5dcb4fad3f09ee3093c to your computer and use it in GitHub Desktop.
Save orisano/29970fa59e60e5dcb4fad3f09ee3093c to your computer and use it in GitHub Desktop.
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
@tompng
Copy link

tompng commented Jan 7, 2017

O(min(arr.size, n)) かもしれないやつ

def array_sample(arr, n)
  replaced = {}
  n.times.map do |i|
    idx = rand arr.size-i
    idx1 = replaced[idx] || idx
    idx2 = arr.size-i-1
    replaced[idx] = replaced[idx2] || idx2
    arr[idx1]
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment