shuffle or mt_rand

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



Hey,

Have a quick question about which is better to get real random values, shuffle or mt_rand.

I am trying to shuffle a deck of cards and reading another thread I saw that after a couple of thousand random generations patterns have been observed using rand()... so its better to use mt_rand().

After i wrote a function (copied below) to get real random cards from a 52 deck, Tijnema from the list kindly sent me a piece of code thats simpler/faster/should or would use less processing and does exactly what my function does except it uses shuffle()...

Any idea which would be better to constantly generate proper random numbers for a long period of time?


========= My original code with mt_rand() ============

function load_cards($no_of_players)
{
    $i=0;
    $cards=array();

while($i<1)
    {

    
        if(empty($cards[0]))
        {
            $cards[]=mt_rand(1,52);
        }
        else
        {            
            $no_of_cards_already_in_array=count($cards);
            $cards_to_be_dealt=$no_of_players * 2; 
            $cards_to_be_dealt=$cards_to_be_dealt + 5;

            if($no_of_cards_already_in_array < $cards_to_be_dealt)
            {
                    $new_generated_card=mt_rand(1,52);

                if(!in_array($new_generated_card,$cards))
                {
                $cards[]=$new_generated_card;
                }
            }else
                {
                // end the loop
                $i=2;
                break; // just in case the above does not break outa the loop.
                }

        }
    }
    return $cards;
}


========== Contributed code ===================
// only generating 5 numbers here
$deck=array(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52);
shuffle($deck);


for($i=0; $i<5; $i++)
{
$card = array_pop($deck);
echo $card."<br>";
}

==============================================


Any comments and suggestions are also welcome.

Thanks!
Ryan





------
- The faulty interface lies between the chair and the keyboard.
- Creativity is great, but plagiarism is faster!
- Smile, everyone loves a moron. :-)
       
---------------------------------
Need a vacation? Get great deals to amazing places on Yahoo! Travel. 

[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux