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:

Start with n=51
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,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include <cmath>
#include <string>
#include <iomanip>
#include <fstream>
#include <cstdlib>
#include <ctime>
#include <vector>

using namespace std;
vector <int> initDeck()
int randomize(int number0_1);
vector<int> shuffleDeck(vector<int> deckVector);

int main()
{
	vector<int> deck = initDeck();
       vector<int> newDeck = shuffleDeck(deck);

		for(int i = 0; i <= 51; i++)
	{
		cout << newDeck[i] << " ";
	}


system("PAUSE");
return 0;
}

vector <int> initDeck()
{
	vector<int> deck(52);
	for(int i=0; i <= 51; i++)
	{
		deck[i] = i;		
	}

	return deck;
}

int randomize()
{
	
		int seed = static_cast<int>(time(NULL));
		srand(seed);
		int card = static_cast<int>((rand()%52));
		return card;
}

vector<int> shuffleDeck(vector<int> 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.