1

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

[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]

4

2 回答 2

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
于 2009-11-23T03:25:14.060 回答
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
于 2009-11-23T10:39:38.320 回答