March 7th, 2009, 05:54 AM
[RESOLVED] Randomly Sorting an Array
Hi, I am trying to write a class that simulates a deck of cards and i am currently working on the shuffle method. I am using a char array to simulate the deck. I remember reading somewhere that there are already methods to randomly sort an array but i wanted to implement the shuffle with my own code. The char array i start with is in a ascending order so it looks like. [2,2,2,2 ... ... K,K,K,K,A,A,A,A]. I was wondering how this algorithm would work and whether others thought it was random enough.
For each index of the array
get a random number within the array bounds.
switch the current char with the char at the random index.
Would this be a good way to shuffle the array. It looks like I will be creating 52 random numbers in total and making 52 swaps total. It does not seem like alot of overhead. I have not tried to write the code yet i just wanted to get some opinions on the alg. and whether or not it would suit. I was also thinking I could run the algo twice on the array.
March 7th, 2009, 06:25 AM
Re: Randomly Sorting an Array
Hey, i wrote the code and ran it. It seems to shuffle the deck pretty well. Ill post results. And i would still like to know whether this would be a good way to shuffle or if there is a more efficient way/ more random way.
* This function Shuffles a Deck of cards.
// initialize a random seed.
srand ( time(NULL) );
//Generate a random number for the swap.
// The random number refers to an index.
random= rand() % 51 ;
//Swapping the chars at the index and the random index.
This is a 1d array. I just have it printing results with 4 columns and 13 rows.
March 7th, 2009, 06:54 AM
Re: [RESOLVED] Randomly Sorting an Array
I found another post about the same topic that covered most of my questions.
Tags for this Thread
Click Here to Expand Forum to Full Width
This is a CodeGuru survey question.