Uniformly distributed integers within a range

Suppose I have a range from 0 to 100, and I want the returned array to contain 3 integers that are evenly distributed within this range, what would be the best way to do this?

For instance:

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

+4
source share
4 answers

Pseudocode:

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: skipped the php tag ...

 //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 */ 
+2
source

you can use array_chunk (), for example, only

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

Exit

 $ php test.php 0 25 50 75 100 

you can get rid of start (0) and end (100) if it is not needed.

+3
source

Here's a groovy solution that gives you the answers you need, you should be able to switch it to any language you use:

 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] 
+2
source

You can use the rand function to get a random value between specific ranges. Use this code. This next function returns a set of elements in an 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() ) ; 
+1
source

Source: https://habr.com/ru/post/1302700/


All Articles