Let X1, X2…. XN (In this case N=52) be the set of N numbers to be shuffled.
1. Set j to N
2. Generate a random number R. (uniformly distributed between 0 and 1)
3. Set k to (jR+1). k is now a random integer, between 1 and j.
4. Exchange Xk and Xj
5. Decrease j by 1.
6. If j > 1, return to step 2.
void Shuffle(int* pArr)
{
int rand;
for(int i=51;i>=0;i--)
{
rand=GenRand(0,i);
swap(pArr[i], pArr[rand]);
}
}
GenRand(int min, int max) generates a random number between min and max.
On Sun, Aug 15, 2010 at 9:10 AM, Dave <[email protected]> wrote:
> @Sharad: Your code does not produce equally probable shuffles. You can
> see this by noting that a[0] is swapped with one of 52 cards, same for
> a[1], a[2], ..., a[51]. Thus, there are 52^52 possible sets of swaps.
> But there are only 52! possible outcomes, and 52^52 / 52! is not an
> integer.
>
> You can verify this experimentally by shuffling a small deck, say 3
> cards. If you do so, you will find that, starting with the deck ABC,
> you get ABC 4/27 of the time, ACB 5/27, BAC 5/27, BCA 5/27, CAB 4/27,
> and CBA 4/27. Thus, some outcomes are 25% more likely than others.
>
> The proper code is
> for(i=1;i<52;++i)
> {
> int r=rand()%(i+1);
> swap(a[i],a[r]);
> }
>
> Dave
>
> On Aug 14, 9:34 pm, sharad kumar <[email protected]> wrote:
> > for(i=0;i<52;++i)
> > {
> > int r=rand()%52;
> > swap(a[i],a[r]);
> >
> > }
> > On Sat, Aug 14, 2010 at 11:46 PM, amit <[email protected]> wrote:
> > > write a program to shuffle an pack of cards in the most efficient way.
> >
> > > --
> > > You received this message because you are subscribed to the Google
> Groups
> > > "Algorithm Geeks" group.
> > > To post to this group, send email to [email protected].
> > > To unsubscribe from this group, send email to
> > > [email protected]<algogeeks%[email protected]>
> <algogeeks%2bunsubscr...@googlegroupsÂ.com>
> > > .
> > > For more options, visit this group at
> > >http://groups.google.com/group/algogeeks?hl=en.
> >
> > --
> > yezhu malai vaasa venkataramana Govinda Govinda
>
> --
> You received this message because you are subscribed to the Google Groups
> "Algorithm Geeks" group.
> To post to this group, send email to [email protected].
> To unsubscribe from this group, send email to
> [email protected]<algogeeks%[email protected]>
> .
> For more options, visit this group at
> http://groups.google.com/group/algogeeks?hl=en.
>
>
--
Rahul singhal
RnD Engineer
Tejas Networks
Mobile- 09916969422
--
You received this message because you are subscribed to the Google Groups
"Algorithm Geeks" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to
[email protected].
For more options, visit this group at
http://groups.google.com/group/algogeeks?hl=en.