Skip to content

Instantly share code, notes, and snippets.

@havenwood
Created July 14, 2020 18:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save havenwood/fa306377e8b7c696caf1d4c8ebecf952 to your computer and use it in GitHub Desktop.
Save havenwood/fa306377e8b7c696caf1d4c8ebecf952 to your computer and use it in GitHub Desktop.
Array#repeated_sample implementation example for #ruby IRC
# 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