Random number generation question

Hi,

I am trying to generate a random number from 0 - 10

And my function keep generating the same number everytime. I put a seed in the constructor of the Wizard class.

The random number generation is being used to generate a random x and y position of the wizards

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 //Constructor
Wizard::Wizard
{
    srand(time(NULL));
}

void Wizard::spawn()
{
	
	
	setWorldLocation(rand() % 10, rand() % 10);

}

void Wizard::printWorldLocation(){
	std::cout << "X Position: " << worldLocation.getX();
	std::cout << " Y Position: " << worldLocation.getY();
}


In the main.cpp I then do the following

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

        std::list<Wizard*> wizards;
	
	Wizard *wizard1 = new Wizard();
        wizard1->spawn();
        wizards.push_back(wizard1);

        Wizard *wizard2 = new Wizard();
        wizard2->spawn();
        wizards.push_back(wizard2);

       	for each (Wizard* wizard in wizards)
	{
	  wizard->printWorldLocation();
	}


Any advice?

Kind Regards
Andy
@Duoas

It would IMO be most excellent if
http://www.cplusplus.com/faq/
appeared on the top left of the screen with the other links to reference, articles etc.



I gather that it is sufficiently complete for general consumption :+), or maybe there is some other reason why there doesn't seem to be a top level link to it?

Regards
Is there a reason why I should only use a seed once in the main rather than seeding each new object made?
@TheIdeasman
It will happen when I get it together enough to finish the FAQ -- at least enough that it can be published. (I hope to have some time to work on it more soon.) [edit] If you want to pick a topic and try your hand at writing some part of the FAQ, or if you find errors in some part and think you can do better, PM me your suggestions. [/edit]

@PapaSmurf
Yes. RNGs work best when they exist for a long time. When you try to reset it over and over you are breaking it -- all the nice characteristics you get are lost and you are left with only the bad.
Last edited on
closed account (48T7M4Gy)
Given the above on RNG's, main should seed and generate the random integer location coordinates to be used in a setWorldLocation(int,int) method rather than the coordinates being seeded and generated within the class method.
You should seed your RNG in main().
You can generate values anywhere you like.
closed account (48T7M4Gy)
I begin with the principle that all men are bores. Surely no one will prove himself so great a bore as to contradict me in this.
Soren Kierkegaard
Kierkegaard + 1!!!!!



:O)
Thanks for all of the answers. This really helped me understand and solved the problem.

Topic archived. No new replies allowed.