-2

I have created a shuffling program that uses a 5X5 array and a vector. The vector should store the values 1 through 25 inclusive and the array should just have 0 for each element. Once the shuffle() function is passed it should randomly position the 1 through 25 values of the vector in the array.

void Match::shuffle() {

    std::vector<int> vec(25);

    int randNum = rand() % (vec.size());

    for (int i = 1; i < 26; i ++) {
            vec.push_back(i);
    }
    for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
            backArr[i][j] = vec.at(randNum);
            vec.erase(vec.begin() + randNum);

            randNum = rand()%vec.size();
            }
    }

}

Drew
  • 101
  • 2

2 Answers2

0

In the last run (i.e., after backArr[i][j] has been set) you remove the last element from the vector and calculate randNum = rand()%vec.size(); which calculates rand() % 0 which will fail.

Just calculate randNum before backArr[i][j] = vec.at(randNum); (also remove the randNum in front of the loops).

Addendum: As pointed out by @infixed in the comments, you also create a vector of 25 (default-initialized) elements and afterwards push 25 additional elements (due to this, the first part of my answer is actually not true). To solve that, you either need to remove the (25) when declaring vec or replace the push_back instructions by corresponding vector accesses (mind the off-by-1).

chtz
  • 17,329
  • 4
  • 26
  • 56
0

why not use std::random_shuffle ?

Renaud
  • 209
  • 2
  • 9