简体   繁体   English

在一定范围内均匀分布的整数

[英]Evenly distributed integers within a range

Lets say I have a range between 0 and 100 and I want an array returned containing 3 integers which are evenly distributed within that range, what would be the best way to do this? 假设我的范围在0到100之间,我希望返回的数组包含3个整数,这些整数均匀分布在该范围内,这样做的最佳方法是什么?

For example: 例如:

Range: 0-100 范围:0-100
Wanted: 3 通缉:3
Returned: 25, 50, 75 退回:25,50,75

you can make use of array_chunk(), eg only 你可以使用array_chunk(),例如

$end=100;
$a = range(0,$end);
$chunk=3;
foreach (array_chunk($a,$end/($chunk+1)) as $s){
     print $s[0]."\n";
}

output 产量

$ php test.php
0
25
50
75
100

you can get rid of the start (0) and end(100) points if not needed. 如果不需要,你可以摆脱开始(0)和结束(100)点。

Pseudo code: 伪代码:

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

edit: missed the php tag... 编辑:错过了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
*/

Here's a solution in groovy that gives the answers you want, you should be able to switch it to whatever language you're using: 这是一个groovy的解决方案,可以提供您想要的答案,您应该可以将其切换为您正在使用的任何语言:

def distributedValues(min, max, wanted) {
   def incrementBy = (max - min)/(wanted + 1)
   (1..wanted).collect { count -> min + (count * incrementBy) }
}


assert distributedValues(0, 100, 1) == [50]
assert distributedValues(0, 100, 3) == [25, 50, 75]
assert distributedValues(0, 100, 4) == [20, 40, 60, 80]
assert distributedValues(0, 100, 5) == [16.6666666667, 33.3333333334, 50.0000000001, 66.6666666668, 83.3333333335]
assert distributedValues(100, 200, 3) == [125, 150, 175]

You can use the rand function to get the random value between the specific ranges. 您可以使用rand函数获取特定范围之间的随机值。 Use this code . 使用此代码。 This following function would return set of element in a array 以下函数将返回数组中的元素集

function array_elements( $start = 0 , $end = 100 , $element =5  )

{

$myarray = array () ;

for ( $i = 0 ; $i <  $element;$i++ )

{

   $myarray[$i]= rand ( $start, $end );

}

return $myarray ;

}

print_r ( array_elements() ) ; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM