可以说我的范围是0到100,并且我希望返回一个包含3个整数的数组,该整数均匀地分布在该范围内,什么是最好的方法?

例如:

范围:0-100
通缉:3
返回:25、50、75

最佳答案

伪代码:

function foo(int rangeLow, int rangeHigh, int wanted)
    int increment=(rangeHigh-rangeLow)/(wanted+1)
    array r=new array()
    for (int i=rangeLow+increment;i<rangeHigh;i+=increment)
        r.push(i)
    return r

编辑:错过了php标签...
//tested:
function foo($wanted=3, $rangeLow=0, $rangeHigh=100){
    $increment=($rangeHigh-$rangeLow)/($wanted+1);
    $r=array();
    for ($i=$rangeLow+$increment;$i<$rangeHigh;$i+=$increment)
        $r[]=$i;
    return $r;
}
/*
  examples:

  call:
      foo ();
  returned:
             [0] => 25
             [1] => 50
             [2] => 75

  call:
      foo (4);
  returned:
             [0] => 20
             [1] => 40
             [2] => 60
             [3] => 80

  call:
      foo (5,50,200);
  returned:
             [0] => 75
             [1] => 100
             [2] => 125
             [3] => 150
             [4] => 175
*/

09-25 17:01