Trouble with assigning dominoes to players for a game

Hi all,

So I'm in the process of making a two player domino game, but I'm having a weird problem of when I get the dominoes from the bag into the players "hands." Here's part of the code in one of my classes that takes care of randomizing the dominoes, and then gives ten to each player.

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
  void CRandom::random(std::vector<data>& myVect)
{
    const int MIN = 1;
    const int MAX = 28;

    for (int i=0; i<= 28; i++)
    {

        data temp;
        temp = myVect[i];

        double myRand = rand()/(1.0 + RAND_MAX);
        int myRand_scaled = (myRand * MAX) + MIN;

        data temp2;
        temp2 = myVect[myRand_scaled];
        myVect[i] = temp2;

        myVect[myRand_scaled] = temp;
    }

}

void CRandom::assign(std::vector<data>& myVect, std::vector<data>& hand1, std::vector<data>& hand2)
{

    for (int i = 0; i < 10; i++)
    {
        data *temp = new data();
        temp-> left = myVect.back().left;
        temp -> right = myVect.back().right;
        hand1.push_back(*temp);
        myVect.pop_back();
        delete temp;
    }

    for(int j =0; j< 10; j++)
    {
        data *temp = new data();
        temp-> left = myVect.back().left;
        temp -> right = myVect.back().right;
        hand2.push_back(*temp);
        myVect.pop_back();
        delete temp;
    }

}


However, when I do this, the domino [0|0] popped up twice, and left out one other domino every time. To test this, I displayed the contents of the bag before any assigning was done, and every piece was there. I can't figure out what's wrong :(

Here's a picture for better explanation: http://i.imgur.com/HT4YiLh.jpg
Is it always the [0|0] domino that repeats itself?
Yes its always [0,0].
It *might* have to do with your index. Your picture shows you have 28 dominoes originally in the bag, but in your random function you access the 29th element of your myVect vector ( i <= 28). That leads me to believe you create a new [0|0] data type, which is then swapped with an existing domino. You probably want your for-loop to look like this:
for (int i = 0; i < 28; ++i)

Also, your random number is generated so oddly. Try int myRand = rand()%MAX;, which will give you a number between [0,MAX), and you won't have to do any strange scaling or use doubles.
Last edited on
And it worked! Thank you so much. And about the random part, the professor wanted us to use that, but I agree it is pretty odd. :/
Topic archived. No new replies allowed.