Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.