0

Possible Duplicate:
How often should I call srand() in a C++ application?

I am trying to implement rolling multiple dice but with my code, even if i create 2+ dice, they always seem to roll the same number. Here's my code:

Dice::Dice() {}

void Dice::roll() 
{
srand(time(0));
setFaceValue((rand() % MAX_FACE_VALUE + 1));
}

int Dice::getFaceValue()
{
return currentFaceValue;
}

void Dice::setFaceValue(int value) 
{
currentFaceValue = value;
}

If I program this into my driver, i get the same number 3 times.

int main()
{
Dice d1, d2, d3;
d1.roll();
cout << d1.getFaceValue() << endl;

d2.roll();
cout << d2.getFaceValue() << endl;

d3.roll();
cout << d3.getFaceValue() << endl;
}
Community
  • 1
  • 1
jsan
  • 1,047
  • 8
  • 20
  • 33

1 Answers1

1

I suspect your 'seed'-ing the RNG uses a time scale that changes slower than how soon your objects b1 - b3 are created; i.e. your time(0) call doesn't change as fast as b1 - b3 are created and call their roll() method.

You can either use, 3 different seed times in the beginning, at object creation time, ensuring a different RNG or use a functions of 1 RNG to make 1-to-1 valued mappings for extracting more RNG numbers.

So in one word go-slow! Adding sleep() calls between the invocations could change things.

Arcturus
  • 550
  • 2
  • 6
  • 1
    `sleep` between `srand` invocations is lame and not entirely random. – alxx Dec 04 '12 at 05:38
  • Well the idea is to use different seed values; you can do it if you prefer with a non-deterministic quantum source. Goodluck finding that off the shelf. – Arcturus Dec 05 '12 at 03:33