dimanche 6 décembre 2020

C++ rand() always giving same TWO values... and then working perfectly

First, I know the basic principle of planting a time seed, and my program's outputs are partially random. But this baffles me.

On subsequent executions of the program, the seven randomly generated values may look like this:

14 14 47 70 84 2 24

14 28 42 52 31 10 12

63 25 4 50 20 27 56

63 19 55 44 65 60 52

14 16 17 40 54 77 4

63 6 79 36 51 85 39

The rest of the values appear random, but the first value is always either 14 or 63. Why is this happening, and how can I make it completely random?

The code is supposed to draw a random Scrabble letter without replacement, with a cout statement added for debugging purposes. The relevant parts are as follows:

string bag = "AAAAAAAAABBCCDDDDEEEEEEEEEEEEFFGGGHHIIIIIIIIIJKLLLLMMNNNNNNOOOOOOOOPPQRRRRRRSSSSTTTTTTUUUUVVWWXYYZ";

int main()
{
    srand(time(0));
    [...]
}

char Player::letter()
{
    int i = rand()%bag.size();
    cout << i << ' ';
    char l = bag[i];
    bag.erase(i,1);
    return l;
}

Any comments are welcome.

EDIT: As requested, a minimal reproducible example, although I'm leaving the original version up for context.

#include <iostream>
using namespace std;

int main()
{
    string bag = "AAAAAAAAABBCCDDDDEEEEEEEEEEEEFFGGGHHIIIIIIIIIJKLLLLMMNNNNNNOOOOOOOOPPQRRRRRRSSSSTTTTTTUUUUVVWWXYYZ";

    srand(time(0));
    for (int a = 0; a < 7; a++)
    {
        int i = rand()%bag.size();
        cout << i << ' ';
        bag.erase(i,1);
    }
    cout << endl;
    return 0;
}



Aucun commentaire:

Enregistrer un commentaire