### Help with shuffling cards (Vector)

I am trying to write a sub-program that takes a deck of 52 cards and will shuffle it up using this algorithm:

Repeatedly:
Generate a random integer between 0 and n. Call it i.
Swap card i and card n in the deck.
Decrease n by 1

However the code that I've written,

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364`` ``````#include #include #include #include #include #include #include #include using namespace std; vector initDeck() int randomize(int number0_1); vector shuffleDeck(vector deckVector); int main() { vector deck = initDeck(); vector newDeck = shuffleDeck(deck); for(int i = 0; i <= 51; i++) { cout << newDeck[i] << " "; } system("PAUSE"); return 0; } vector initDeck() { vector deck(52); for(int i=0; i <= 51; i++) { deck[i] = i; } return deck; } int randomize() { int seed = static_cast(time(NULL)); srand(seed); int card = static_cast((rand()%52)); return card; } vector shuffleDeck(vector deckVector)//deckVector is the original deck in order { int temp, n, i, s; n = 51; for(n = 51; n >=0 ; n--) { // following code should swap out random values for the highest vector place i = randomize();// randomize(0) generates random number between 0 and 51 temp = deckVector[n]; deckVector[n] = deckVector[i]; deckVector[i] = temp; } return deckVector;// this is supposed to be the shuffled deck }``````

when I output the new vector, only produces this output(note- it is a random number every time, but it just repeats over and over):

 ```8 8 8 8 8 8 8 8 0 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 8```

or:

 ```22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 0 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22 22```

Any help in explaining why this doesn't work would be appreciated, and any pointers toward the general right direction would be nice.
Last edited on
1) I think your randomize function is not good.
2) line 11 should be `deckVector[n] = deckVector[i];`
I updated it for the full code, so that maybe someone can troubleshoot it. I fixed that section of the code now line 60: ` deckVector[n] = deckVector[i];`, what could be wrong with my randomize function? It seems to give a different number everytime..
Last edited on
The problem is that you are seeding your RNG multiple times. As modern hardware is fast, no measurable time passes between function calls in shuffleDeck and you are essentually seeding RNG with the same value each call. Remember, you should seed only once. Ideally at the start of program.
That sems to have fixed the problem, thank you MiiNiPaa!
Topic archived. No new replies allowed.