小编Ale*_*ini的帖子

在数组中分配范围

我需要在一个范围内创建一个数字数组,例如:

[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
Run Code Online (Sandbox Code Playgroud)

分布式(1,5,10,真)=> [1,1,1,2,2,3,3,4,4,4] #WRONG应为[1,1,2,2,3,3, 4,4,5,5]

分布(5,1,5,真)=> [5,4,3,2,1] #OK

分发(1,5,3,真)=> [4,5,5] #WRONG应该是[1,3,5]

ruby refactoring distribution range

1
推荐指数
1
解决办法
652
查看次数

标签 统计

distribution ×1

range ×1

refactoring ×1

ruby ×1