在数组中分配范围

时间:2009-11-23 02:11:05

标签: ruby refactoring range distribution

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

[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
  

分发(1,5,10,真)   =&GT; [1,1,1,2,3,3,4,4,4] #WRONG应为[1,1,2,2,3,3,4,4,5,5]

     

分发(5,1,5,真)   =&GT; [5,4,3,2,1] #OK

     

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

2 个答案:

答案 0 :(得分:5)

怎么回事:

def distribute(min,max,items)
  min,max = [min,max].sort
  (0...items).map {|i| (min + i * (max - min) / (items-1.0)).round}
end

或者如果你真的需要int / float标志:

def distribute(min,max,items,ints)
  min,max = [min,max].sort
  a = (0...items).map {|i| min + i * (max - min) / (items-1.0)}
  ints ? a.map {|i| i.round} : a
end

如果您向后提供参数,如果您确实需要这样做,那么

def distribute(min,max,items,ints)
  usemin,usemax = [min,max].sort
  diff = usemax - usemin
  a = (0...items).map {|i| usemin + i * diff / (items-1.0)}
  a.map! {|i| i.round} if ints
  min != usemin ? a.reverse : a
end

答案 1 :(得分:0)

稍微纠正......当array_size为0时

  def distribute(start_value, end_value, array_size, want_ints)
    diff = 1.0 * (end_value - start_value)
    n = [array_size-1, 1].max

    (0..(array_size-1)).map { |i|
        v = start_value + i * diff / n
        want_ints ? v.round : v
    }    
  end