Jump to content

[SOLVED] Sorting and optimisation help


laqutus

Recommended Posts

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

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.

 

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.