Created
July 14, 2020 18:34
-
-
Save havenwood/fa306377e8b7c696caf1d4c8ebecf952 to your computer and use it in GitHub Desktop.
Array#repeated_sample implementation example for #ruby IRC
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
# frozen_string_literal: true | |
require 'securerandom' | |
module RepeatedSample | |
refine Array do | |
def repeated_sample(sample_size = 1) | |
m = 1 | |
limit = size | |
while limit * size <= 0x100000000 | |
limit *= size | |
m += 1 | |
end | |
result = [] | |
while m <= sample_size | |
rs = SecureRandom.random_number(limit) | |
is = rs.digits(size) | |
(m - is.length).times { is << 0 } | |
result.concat values_at(*is) | |
sample_size -= m | |
end | |
if sample_size.positive? | |
rs = SecureRandom.random_number(limit) | |
is = rs.digits(size) | |
if is.length < sample_size | |
(sample_size - is.size).times { is << 0 } | |
else | |
is.pop while sample_size < is.length | |
end | |
result.concat values_at(*is) | |
end | |
result | |
end | |
end | |
end | |
using RepeatedSample | |
pp [*'a'..'z', *'A'..'Z', *'0'..'9'].repeated_sample(6) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment