2

I have the following structure to randomly generate a field of integers:

GameManager::GameManager(){
    srand(time(NULL));
}

void GameManager::newGame(int sizen, int sizem) {

//ETC
    for(int i = 0; i < sizen; ++i){
        _gameField[i].resize(sizem);
        for(int j = 0; j < sizem; ++j){
            _gameField[i][j] = RandomColor(difficulty);
        }
    }
}

int GameManager::RandomColor(Difficulty diff){
    if(diff == Easy){
        return rand()%4+1;
    } else if(diff == Medium) {
        return rand()%5+1;
    }else{
        return rand()%6+1;
    }
}

This however, only generates the same field of numbers each time, as if the seeding didn't work. If I put the seeding in newGame(), it does generate different random numbers each time. Why doesn't the seeding work in the constructor?

EDIT

See the class definition here:

class GameManager : public QObject
{
    Q_OBJECT
public:
    GameManager();
    ~GameManager();

    int Size_n = 12;
    int Size_m = 7;

    Difficulty difficulty = Easy;

    void newGame(int sizen, int sizem);
    QVector<QVector<int> > _gameField;
    QVector<QPair<int,int> > _taboo;

private:
    int RandomColor(Difficulty diff);
};
lte__
  • 7,175
  • 25
  • 74
  • 131
  • 1
    don't put it in the constructor. [Call it only once at the beginning of the program](https://stackoverflow.com/q/7343833/995714) – phuclv Jun 05 '17 at 08:59
  • OK I won't, but why doesn't it work from there? – lte__ Jun 05 '17 at 09:00
  • 2
    Could you please create a [mcve]? – Rakete1111 Jun 05 '17 at 09:00
  • because it'll reseed when each new object is created. Anyway keep away from `rand()` and use [`std::uniform_int_distribution`](https://stackoverflow.com/q/13445688/995714) to avoid bias – phuclv Jun 05 '17 at 09:12
  • But my `GameManager` object only gets created once. – lte__ Jun 05 '17 at 09:14
  • 1
    Please post a [mcve], and also a beginning section of the sequence of numbers it generates. – n. m. could be an AI Jun 05 '17 at 09:19
  • Possible duplicate of [srand() — why call it only once?](https://stackoverflow.com/questions/7343833/srand-why-call-it-only-once) – 463035818_is_not_an_ai Jun 05 '17 at 09:37
  • 1
    put a breakpoint in the constructor, to see that it actually gets called, and how many times – sp2danny Jun 05 '17 at 09:41
  • unless you're using singleton, you can't guarantee it'll be only seeded once. But as I said, [`rand` is bad](https://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful) if you don't know how to use it properly (which you don't, because you clearly have bias in your code) or need more security. Use C++'s uniform distributor instead – phuclv Jun 05 '17 at 12:07
  • @LưuVĩnhPhúc I'd argue vehemently for not using `rand` anytime if any randomness is required. But this might not be one. – Passer By Jun 05 '17 at 12:22

0 Answers0