module Kernel
def random(range)
first = range.first
last = range.exclude_end? ? range.last - 1 : range.last
max = (last - first + 1) * (first + last) / 2
result = rand(max) + 1
for i in range
small = i > first ? ((i - first) * (first + i - 1) / 2) : 0
large = i > first ? ((i - first + 1) * (first + i) / 2) : first
break if result > small and result <= large
#return i if result > small and result <= large
end
return last - i + first
end
end
#代码测试
a = []
1000.times{
r = random(20..40)
if a[r].nil?
a[r] = 0
end
a[r] += 1
}
a.delete(nil)
p a
exit
module Kernel
def random(range)
first = range.first
last = range.exclude_end? ? range.last - 1 : range.last
max = (last - first + 1) * (first + last) / 2
result = rand(max) + 1
for i in range
small = i > first ? ((i - first) * (first + i - 1) / 2) : 0
large = i > first ? ((i - first + 1) * (first + i) / 2) : first
break if result > small and result <= large
#return i if result > small and result <= large
end
return last - i + first
end
end
#代码测试
a = []
1000.times{
r = random(20..40)
if a[r].nil?
a[r] = 0
end
a[r] += 1
}
a.delete(nil)
p a
exit