Re: Shuffling a linked list
- From: Pascal Bourguignon <pjb@xxxxxxxxxxxxxxxxx>
- Date: Fri, 29 Dec 2006 18:07:16 +0100
"A. Farber" <Alexander.Farber@xxxxxxxxx> writes:
Hello,
I have a doubly-linked list of 32 playing cards, which I'd like to
randomly and evenly (!) shuffle.
(For several reasons I'm not using an array, which I could go
through once, keeping swapping cards at random positions.)
I have a list head with 2 pointers - to the very 1st and to the
last elements and I have 2 macros to insert an element at the
"head" or at the "tail".
Does anybody please have a good algorithm for me?
I'm thinking of having an integer variable i which I'd increase
by one while going through my list. And if rand(i) < 1 then
I'd move that element at the "head" of the list. Which should
give each card a 1/32 possibility to land at the "head" position.
Choose one random element in the list, remove it and put it in a new
list. Repeat until the original list is empty.
--
__Pascal Bourguignon__ http://www.informatimago.com/
In deep sleep hear sound,
Cat vomit hairball somewhere.
Will find in morning.
.
- Follow-Ups:
- Re: Shuffling a linked list
- From: Richard Harter
- Re: Shuffling a linked list
- References:
- Shuffling a linked list
- From: A. Farber
- Shuffling a linked list
- Prev by Date: Re: Shuffling a linked list
- Next by Date: Re: help in understanding this problem (beginner)
- Previous by thread: Re: Shuffling a linked list
- Next by thread: Re: Shuffling a linked list
- Index(es):
Relevant Pages
|