2009-11-23 28 views
1

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

[1..5] 10次= [1,1,2,2,3,3,4, -1,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,真) => [1,1,1,2,2,3,3,4,4,4 ] #WRONG应该是[1,1,2,2,3,3,4,4,5,5]

distribute(5,1,5,true) => [5,4,3, 2,1] #OK

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

回答

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 
+1

而不是复杂的特殊情况下的算法,你可以短路的方法:'返回[]除非array_size> 0'。至少对我来说,这样更容易理解代码。 – FMc 2009-11-23 14:08:35

5

怎么回合这样的:

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

或者,如果你真的需要整型/浮点标志:

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 
+0

而显然,如果您知道按照正确的顺序获取参数,则可以省略min,max =部分... – 2009-11-23 04:15:23

+0

也许我误解了这个问题,但是这个答案对于OP的第二个问题似乎并不正确用例:'distribute(5,1,5,true)=> [5,4,3,2,1]'。 – FMc 2009-11-23 14:14:10

+0

是的。我只是在这种情况下添加了另一个变体。 – 2009-11-23 21:34:07