Re: Random numbers with no duplicates
From: David White (no_at_email.provided)
Date: 09/27/04
- Next message: Chris \( Val \): "Re: string upper, string lower, string subthisforthat"
- Previous message: Gary Labowitz: "Re: Random numbers with no duplicates"
- In reply to: Gary Labowitz: "Re: Random numbers with no duplicates"
- Next in thread: Gary Labowitz: "Re: Random numbers with no duplicates"
- Reply: Gary Labowitz: "Re: Random numbers with no duplicates"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Mon, 27 Sep 2004 16:14:30 +1000
"Gary Labowitz" <glabowitz@comcast.net> wrote in message
news:oJydnQObS4S3CsrcRVn-tA@comcast.com...
> "David White" <no@email.provided> wrote in message
> news:n7I5d.2844$pl.50584@nasal.pacific.net.au...
> > That's not right. The last card would always be swapped with itself,
> leaving
> > the array as it is.
> >
> > BTW, another feature of this algorithm is that you only need to fill the
> > array once for any number of repeat uses. Once all values have been
> > selected, they are all still in the array. They are in some
pseudo-random
> > order, but that doesn't matter because the starting order is irrelevant
to
> > the randomness of the selections. Just reset the range to 10 and repeat
> the
> > process.
> If on the last step the tenth card is swapped with a randomly selected
> location, there is a pretty good chance that it will not be swapped with
> itself.
On the last step there's only one location left that can be selected.
> The algorithm is to swap each location in the array (from 0 - (n-1)) with
> randomly selected locations in the range 0 - (n-1).
No, the algorithm is to randomly generate an index in the range 0..N-1
inclusive, where N is the number of values remaining, and swap the value at
the selected location with the value at N-1. Then you decrement N, which
places the selected value outside the selectable range for the next
selection. Here are the relevant parts from a card dealer class:
CardDeck::CardDeck()
{
srand(/* suitable seed */);
cards_remaining = N; // e.g., 52
for(int icard = 0; icard < N; ++icard)
deck[icard] = icard;
}
int CardDeck::DealCard()
{
if(cards_remaining == 0)
return -1; // error, deck empty
int icard = rand() % cards_remaining; // crude, and not ideal, but
good enough for most purposes
int card = deck[icard];
deck[icard] = deck[cards_remaining-1];
deck[cards_remaining-1] = card;
--cards_remaining;
return card;
}
void CardDeck::Shuffle() // i.e., to re-deal
{
cards_remaining = N;
}
DW
- Next message: Chris \( Val \): "Re: string upper, string lower, string subthisforthat"
- Previous message: Gary Labowitz: "Re: Random numbers with no duplicates"
- In reply to: Gary Labowitz: "Re: Random numbers with no duplicates"
- Next in thread: Gary Labowitz: "Re: Random numbers with no duplicates"
- Reply: Gary Labowitz: "Re: Random numbers with no duplicates"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|