laqutus Posted October 2, 2008 Share Posted October 2, 2008 I have a pretty simple question really, I have been coding for about 5 months now and I want to progress forward but am being blocked because I keep writing things they why I have learnt but I know its not the best method. So my question is: Is there a better way to format the following code mine is sluggish: Its for a lottery number generator. $b1 = rand(1, 49); $b2 = rand(1, 49); $b3 = rand(1, 49); $b4 = rand(1, 49); $b5 = rand(1, 49); $b6 = rand(1, 49); // Check that none of the numbers are identical, $b1 is the leading ball while ($b2 == $b1) { $b2 = rand(1, 49);} while ($b3 == $b1 || $b3 == $b2) { $b3 = rand(1, 49);} while ($b4 == $b1 || $b4 == $b2 || $b4 == $b3) { $b4 = rand(1, 49);} while ($b5 == $b1 || $b5 == $b2 || $b5 == $b3 || $b5 == $b4) { $b5 = rand(1, 49);} while ($b6 == $b1 || $b6 == $b2 || $b6 == $b3 || $b6 == $b4 || $b6 == $b5) { $b6 = rand(1, 49);} // Set array & sort results in ASC order $n = array( ); $n[]="$b1"; $n[]="$b2"; $n[]="$b3"; $n[]="$b4"; $n[]="$b5"; $n[]="$b6"; sort($n); print $db[0]; print " , "; print $db[1]; print " , "; print $db[2]; print " , "; print $db[3]; print " , "; print $db[4]; print " , "; print $db[5]; echo "<br>"; Link to comment https://forums.phpfreaks.com/topic/126766-solved-sorting-and-optimisation-help/ Share on other sites More sharing options...
trq Posted October 2, 2008 Share Posted October 2, 2008 Not tested. <?php $numbers = array(); while (count($numbers) < 6) { $tmp = rand(1,49); if (!in_array($tmp,$numbers)) { array_push($numbers,$tmp); } } echo implode(' , ',$numbers); ?> Link to comment https://forums.phpfreaks.com/topic/126766-solved-sorting-and-optimisation-help/#findComment-655651 Share on other sites More sharing options...
Zhadus Posted October 2, 2008 Share Posted October 2, 2008 Learn the awesome use of loops. And arrays are more friendly than you think. <?php function getNum($min, $max) { $num = rand($min, $max); return $num; } for ($x = 0; $x < 6; $x++) { $b[] = getNum(1, 49); } for ($x = 1; $x < 6; $x++) { while ($b[$x] == $b[($x-1)]) { $b[$x] = getNum(1, 49); } } sort($b); $output = implode(", ", $b); echo $output; ?> Ack, beat me to it. Same idea, just a little different route. Link to comment https://forums.phpfreaks.com/topic/126766-solved-sorting-and-optimisation-help/#findComment-655657 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.