1
0
Fork 0
mirror of https://github.com/ruby/ruby.git synced 2022-11-09 12:17:21 -05:00

less random generations in Random::Formatter#choose.

git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@60309 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
akr 2017-10-21 16:12:46 +00:00
parent 2c27e52f8e
commit 6cba29b422
2 changed files with 29 additions and 4 deletions

View file

@ -243,7 +243,31 @@ module Random::Formatter
# +NotImplementedError+ is raised. # +NotImplementedError+ is raised.
private def choose(source, n) private def choose(source, n)
size = source.size size = source.size
n.times.map {source[random_number(size)]}.join('') m = 1
limit = size
while limit * size <= 0x100000000
limit *= size
m += 1
end
result = ''.dup
while m <= n
rs = random_number(limit)
is = rs.digits(size)
(m-is.length).times { is << 0 }
result << source.values_at(*is).join('')
n -= m
end
if 0 < n
rs = random_number(limit)
is = rs.digits(size)
if is.length < n
(n-is.length).times { is << 0 }
else
is.pop while n < is.length
end
result.concat source.values_at(*is).join('')
end
result
end end
ALPHANUMERIC = [*'A'..'Z', *'a'..'z', *'0'..'9'] ALPHANUMERIC = [*'A'..'Z', *'a'..'z', *'0'..'9']

View file

@ -144,9 +144,10 @@ end
end end
def test_alphanumeric def test_alphanumeric
65.times do |idx| 65.times do |n|
an = @it.alphanumeric an = @it.alphanumeric(n)
assert_match(/^[0-9a-zA-Z]+$/, an) assert_match(/^[0-9a-zA-Z]*$/, an)
assert_equal(n, an.length)
end end
end end