Jump to content

2 Random Numbers that cannot be the same?


TJMAudio

Recommended Posts

  • 1 month later...
<?php

$nums = array();

$min = 1;
$max = 10;

$total = 4;

if ( ($max-$min) < $total )
die('Let\'s avoid infinite loops...');

while ( count($nums) < $total ) {

$num = mt_rand($min, $max);
while ( in_array($num, $nums) )
	$num = mt_rand($min, $max);
$nums[] = $num;

}

print_r( $nums );

?>

Here's my favorite way

 

$max = 12;
$set = range(1,$max);
for ($i = 0; $i < 4; $i++) {
  $choice = rand(0,$max-1);
  $rand_set[] = $set[$choice];
  $set[$choice] = $set[$max-1];
  $max--;
}
print "Selected: " . implode(', ', $rand_set) . "\n";

 

The idea is to remove a random element, move the last element into that empty spot, then reduce the array size by 1.  This method works well for lower level languages like C also.

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.