Jump to content

making random unique numbers with separation


sk121506

Recommended Posts

I can get unique random numbers and as many as i want within the specific parameters i choose. What i would like to add with a step further is separate these unique random numbers by 4. For example if i chose what the code shows below with 10 unique random numbers between 100, the separation would have it so the numbers could not be within 4 of each other. A final display of this separation would be like.... 6,20,88,44, etc.... and NOT 6,8,98,95, etc. Thanks in advance for anyone who can help me with this problem.

 

$numbers = array();

for($i=1; $i <= 10; $i++) {

  $num = rand(1,100);

  while(in_array($num, $numbers)) {

      $num = rand(1,100);

  } 

  $numbers[] = $num;

}

 

echo implode(' ', $numbers);

 

you just need a while check to see if the number generated is a 4 or more bigger than the one generated previously if it is not generate a new number until it is

 

$tot = $newNum - $oldNum;

while($tot < 4)

{

  $newNum = rand(1,100);

  $tot = $newNum - $oldNum;

}

 

summin along them lines

well i thought of this approach, but it may not work. Say, a few numbers are drawn and they are all fair, say 13,18,77, and then 93. If the next random number is 20, instead of looking at the previous number, 93, you would need to compare it to all the numbers already drawn. Hope i'm not confusing anyone in this idea.

This will do it, there may be a more elegant, mathematical solution, but I suck at math.  :D

<?php
$randNums[] = mt_rand(1,100);
$i=1;
while ($i<=3) {
    
    $test  = mt_rand(1,100);
    $items = range($test - 4,$test+4);
    $a     = array_intersect($randNums,$items);
    if (empty($a)) {
        $randNums[]  = $test;
        ++$i;
    } else {
        echo "<p>$test was too close</p>";
    }
}
print_r($randNums);
?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.