Re: random elements of an array
| From: | Nicole Amashta | Date: | Fri, 22 Mar 2002 15:48:00 +0000 |
| Subject: | Re: random elements of an array | ||
| References: | 1 2 | Groups: | php.windows |
| Request: | Send a blank email to php-windows+get-12731@lists.php.net to get a copy of this message | ||
Oh, oops ... one line should not be in there ... remove this line from the
randomize function:
<snip>
$usedIndexesArray[$i] = $randomIndex;
</snip>
It should not be there. I started to keep track of the indexes used, but i
found better way to do it. So remove that line, it does nothing.
-Nicole
"Nicole Amashta" <430ntr3k@bellsouth.net> wrote in message
news:20020322153412.57199.qmail@pb1.pair.com...
> And, now, in PHP ...
>
> <?
> /*
> By Eva Nicole Amashta
> 2002.03.22
> Testing randomizing an array.
> */
>
>
> $myArray = array( 1, 12, 32, 14, 52, 9 );
>
> echo "<p>Before randomized ... <p>";
>
> ## print out array before randomized
> for($i=0; $i<count($myArray); $i++)
> {
> echo $myArray[$i] . " ";
> }
>
> reset( $myArray );
>
> $myArray = randomize(&$myArray);
>
> ## now print out the array to see after randomized
>
> echo "<p>After randomized ... <p>";
>
> for($i=0; $i<count($myArray); $i++)
> {
> echo $myArray[$i] . " ";
> }
>
>
> //////////////////////
> function randomize($someArray) ## uses rand()
> {
> $newArray = array();
> $sizeOfArray = count($someArray);
>
> for($i=0; $i<$sizeOfArray; $i++ )
> {
> $randomIndex = rand(0, $sizeOfArray-1);
> while ( count($newArray) > 0 &&
> in_array($someArray[$randomIndex],$newArray) )
> {
> $randomIndex = rand(0, $sizeOfArray-1);
> }
>
> $newArray[$i] = $someArray[ $randomIndex ];
>
> $usedIndexesArray[$i] = $randomIndex;
> }
>
> return $newArray;
> }
> ?>
>
> I have tested this. It works, Even after you refresh the page. Try it!
>
> Nicole
> www.aeontrek.com
>
>
>
> "B.A.T. Svensson" <B.A.T.Svensson@lumc.nl> wrote in message
> news:27E647E5629ED211BF78009027289C6303C1B777@mail1...
> > You can completely randomize an array with n elements in n operations,
by
> > using the following brute force approach:
> >
> > void ScrambleIntList(int *pnElements, int nLen)
> > {
> > for (nLoop = 0, nLoop<nLen; nLopp++) {
> >
> > // Pic a random element
> > int nRandomPic = nLen * rand();
> >
> > file://Swap current element with the random pic
> > int nTemp = pnElement[nLoop];
> > pnElement[nLoop] = Element[nRandomPic];
> > pnElement[nRandomPic] = nTemp;
> >
> > }
> > }
> >
> > /Anders
> >
> > >-----Original Message-----
> > >From: Afan Pasalic [mailto:afan@sprout.net]
> > >Sent: Thursday, March 21, 2002 9:17 PM
> > >To: php-windows@lists.php.net
> > >Subject: [PHP-WIN] random elements of an array
> > >
> > >
> > >Hi,
> > >
> > >My problem is: if I have an array (e.g. 1, 2, 3, 4, 5, 6, 7,
> > >8, 9), how I can "shake" the array and get randomized order of
> > >the same array (e.g. 5, 8, 1, 9, 3, 4, 7, 2, 6)?
> > >
> > >Thanks for any help!
> > >
> > >
> > >Afan
> > >
>
>