0

I am currently working on code that generates random numbers on a 4 by 4 board. I have a board.h, board.cpp and a main.cpp file. In main.cpp I include Board.h.

In Board.cpp is where I construct the board using rand();. In main I create two instances of the class where I get the two boards

My issue is that if I use srand((unsigned int)time(NULL)) in main I'll generate the same two different boards. Whereas if I use srand((unsigned int)time(NULL)) in Board.cpp I get two identical boards. One solution I've found is sleeping for a second, but I am losing a lot of time by doing that and wanted to know if there's a better solution.

phuclv
  • 37,963
  • 15
  • 156
  • 475
zeltath
  • 33
  • 3
  • 2
    Use [better random number generators than `rand()`](https://en.cppreference.com/w/cpp/numeric/random)? – Nate Eldredge Oct 05 '21 at 03:02
  • 3
    You need to do one single `srand` at program startup. Don't do more than one, and you'll get different boards. – Jeffrey Oct 05 '21 at 03:08
  • You seem to have already found the solution – call `srand` only once. What's wrong with that solution? – molbdnilo Oct 05 '21 at 03:17
  • 2
    Handy reading: [srand() — why call it only once?](https://stackoverflow.com/questions/7343833/srand-why-call-it-only-once) – user4581301 Oct 05 '21 at 03:29
  • @molbdnilo I just tried it again and it worked! It seemed I had been calling srand() a second time and didn't notice. – zeltath Oct 05 '21 at 07:20
  • @zeltath You created two boards, and each board called `srand`. – molbdnilo Oct 05 '21 at 07:33
  • *"It seemed I had been calling srand() a second time and didn't notice."* Maybe it's time to post a [mre], if the dupe mentioned in the comments doesn't answer your question. – Bob__ Oct 05 '21 at 08:28

0 Answers0