Shuffling a linked list
- From: "A. Farber" <Alexander.Farber@xxxxxxxxx>
- Date: 29 Dec 2006 07:56:32 -0800
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.
Regards
Alex
PS: My program is actually in C and I'm using TAILQ_ macros for
my list: http://www.openbsd.org/cgi-bin/man.cgi?query=queue
.
- Follow-Ups:
- Re: Shuffling a linked list
- From: Robert Maas, see http://tinyurl.com/uh3t
- Re: Shuffling a linked list
- From: Richard Heathfield
- Re: Shuffling a linked list
- From: Pascal Bourguignon
- Re: Shuffling a linked list
- From: Oliver Wong
- Re: Shuffling a linked list
- Prev by Date: Re: Lindsay
- Next by Date: Re: .indd .cpt .psd .ps .eps .ai file formats help need
- Previous by thread: Lindsay
- Next by thread: Re: Shuffling a linked list
- Index(es):
Relevant Pages
|