我需要在一个范围内创建一组数字,例如:
[1..5] 10 次 = [1,1,2,2,3,3,4,4,5,5]
[1..5] 5 次 = [1,2,3,4,5]
[1..5] 3 次 = [1,3,5]
def distribute(start_value, end_value, times, is_integer)
array = Array.new(times-1)
min_value = [end_value,start_value].min
max_value = [end_value,start_value].max
if max_value-min_value<times
factor = (max_value-min_value).abs/(array.size).to_f
else
factor = (max_value-min_value).abs/(array.size-1).to_f
end
for i in 0..array.size
v = [ [max_value, factor*(i+1)].min, min_value].max
is_integer ? array[i] = v.round : array[i] = v
end
start_value < end_value ? array : array.reverse
end
Distribute(1, 5, 10, true) => [1, 1, 1, 2, 2, 3, 3, 4, 4, 4] #错误应该是 [1,1,2,2,3,3, 4,4,5,5]
分发(5, 1, 5, true) => [5, 4, 3, 2, 1] #OK
Distribute(1, 5, 3, true) => [4, 5, 5] #错误应该是 [1, 3, 5]