Jump to content

Generate Distinct Random Numbers


barkster

Recommended Posts

I'm trying to build a simple lotto number generator.  I'm having a hard time getting it to not use a number that is has already picked.  I'm thinking I need a recursive function or something 

 

<?php
function random56() {
srand ((double) microtime( )*1000000);
$random_number = rand(1,56);
$n = $random_number;
return $n;
}

function random46() {
srand ((double) microtime( )*1000000);
$random_number = rand(1,46);
$n = $random_number;
return $n;
}

if($_POST['count']!='') {
	for($c=1;$c<=$_POST['count'];$c++) {
		$row = "";
		for($i=0;$i<=4;$i++) {
			$g ="";
			while (!strrpos($g, $row)) {
				$g = random56();
			}
			$row .= $g . ", ";
		}
		$row .= "<strong>".random46()."</strong>";
		$ary[$c] = $row;
	}
}
?>

Link to comment
https://forums.phpfreaks.com/topic/41320-generate-distinct-random-numbers/
Share on other sites

<?php
function pickNumbers($min, $max, $num)
{
    $numbers = range($min, $max);
    $picks = array();
    for ($i = 0; $i < $num; $i++)
    {
        shuffle($numbers);
        $picks[] = array_pop($numbers);
    }
    return $picks;
}
$picks = pickNumbers(1, 20, 6);
print_r($picks);
?>

Thanks for the quick reply, that is much simplier.  How could I loop through each array and print out formated.  I get two arrays when I print it

 

Array ( [0] => 37 [1] => 52 [2] => 42 [3] => 15 [4] => 34 [5] => 29 ) Array ( [0] => 12 [1] => 17 [2] => 7 [3] => 43 [4] => 19 [5] => 42 )

 

I'd like to get

37,52,42,15,34,29

 

Thanks

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.