Random number generation question

Nov 7, 2015 at 7:33pm
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
Nov 7, 2015 at 9:28pm
Nov 7, 2015 at 10:04pm
@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
Nov 7, 2015 at 10:17pm
Is there a reason why I should only use a seed once in the main rather than seeding each new object made?
Nov 7, 2015 at 10:56pm
@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 Nov 7, 2015 at 10:57pm
Nov 8, 2015 at 4:24am
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.
Nov 8, 2015 at 4:31am
You should seed your RNG in main().
You can generate values anywhere you like.
Nov 8, 2015 at 5:32am
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
Nov 8, 2015 at 7:16pm
Kierkegaard + 1!!!!!



:O)
Nov 11, 2015 at 8:16pm
Thanks for all of the answers. This really helped me understand and solved the problem.

Topic archived. No new replies allowed.