Need Help with Randomness

I'm having difficulty coming up with the correct code for the following problem.

Let's say I have 100 cupcakes and I have to randomly give it out to random boys and girls. The program will then have to determine which group has the majority.

What would be the easiest approach?

1
2
int cake = rand() % 100;
	cout << cake << endl;


I'm trying to use this code to generate a random number between 1 and 100 and using if then statements to figure out which group received more. Am I on the right track cause I'm really confused right now. Hope this is easy to understand.

I guess what I don't understand is how am I supposed to divide 100 randomly between two groups (boys and girls).
You could do something like this :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <windows.h>
#include <iostream>
#include <time.h>

bool _bRandom=false;
int random(int min, int max) {
	if(_bRandom==false) {
		_bRandom=true;
		srand(time(0));
	}
	return (min+(rand()%max));
}

int main() {
	if(random(0, 100) <= 50) {
		std::cout << "Boys Win!" << std::endl;
	}else {
		std::cout << "Girls Win!" << std::endl;
	}
	std::cin.sync();
	std::cin.get();
	return 0;
}
1
2
3
4
5
6
7
8
9
int main()
{
     srand(time(NULL));
     if(rand()%2 == 0)
           std::cout<< "Boys";
     else
           std::cout<<"Girls";
     return 0;
}


@xismn: It's probably better to declare _bRandom as a static variable in the scope of random.

EDIT: If you actually need to allocate cupcakes individually you can create two integers, boys and girls, and just iterate over a loop which increments one of the two randomly 100 times.
Last edited on
Topic archived. No new replies allowed.