Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

For example:

Range: 0-100
Wanted: 3
Returned: 25, 50, 75

like image 912
DanCake Avatar asked Mar 01 '10 02:03

DanCake


2 Answers

Pseudo code:

function distributeIntegers(int wanted, int rangeLow, int rangeHigh)
    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:

function distributeIntegers($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:
      distributeIntegers();
  returns:
             [0] => 25
             [1] => 50
             [2] => 75

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

  call:
      distributeIntegers(5, 50, 200);
  returns:
             [0] => 75
             [1] => 100
             [2] => 125
             [3] => 150
             [4] => 175
*/
like image 136
Cam Avatar answered Nov 05 '22 22:11

Cam


you can make use of array_chunk(), eg only

$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.

like image 3
ghostdog74 Avatar answered Nov 05 '22 22:11

ghostdog74