TJMAudio Posted April 29, 2008 Share Posted April 29, 2008 I am trying to generate two random numbers, but have a check to make sure the first number isn't the same as the second. The numbers will range between 1 and 12. I have tried multiple ways of doing this, but cannot figure out an easy solution. Any ideas? Quote Link to comment https://forums.phpfreaks.com/topic/103460-2-random-numbers-that-cannot-be-the-same/ Share on other sites More sharing options...
moselkady Posted April 29, 2008 Share Posted April 29, 2008 If it is just 2 number, you can try this: <?php $a = $b = rand(1,12); while ($b == $a) $b=rand(1,12); ?> Quote Link to comment https://forums.phpfreaks.com/topic/103460-2-random-numbers-that-cannot-be-the-same/#findComment-529801 Share on other sites More sharing options...
TJMAudio Posted June 4, 2008 Author Share Posted June 4, 2008 Alright, I have tried everything on this one. Now I need 4 random numbers that can't be the same. I just cannot seem to figure this out. Quote Link to comment https://forums.phpfreaks.com/topic/103460-2-random-numbers-that-cannot-be-the-same/#findComment-557936 Share on other sites More sharing options...
discomatt Posted June 4, 2008 Share Posted June 4, 2008 <?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 ); ?> Quote Link to comment https://forums.phpfreaks.com/topic/103460-2-random-numbers-that-cannot-be-the-same/#findComment-557947 Share on other sites More sharing options...
Barand Posted June 4, 2008 Share Posted June 4, 2008 <?php $set = range(1,12); shuffle($set); $rand_set = array_slice($set,0,4); Quote Link to comment https://forums.phpfreaks.com/topic/103460-2-random-numbers-that-cannot-be-the-same/#findComment-557951 Share on other sites More sharing options...
discomatt Posted June 4, 2008 Share Posted June 4, 2008 Nice Barand Quote Link to comment https://forums.phpfreaks.com/topic/103460-2-random-numbers-that-cannot-be-the-same/#findComment-557963 Share on other sites More sharing options...
btherl Posted June 5, 2008 Share Posted June 5, 2008 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. Quote Link to comment https://forums.phpfreaks.com/topic/103460-2-random-numbers-that-cannot-be-the-same/#findComment-558019 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.