I am stuck with a problem that I originally thought would be so easy to solve!
I have an enum with 4 values (empty, male, female, child). I have an array which corresponds to 50 seats. So, I would like to put men, women, and children in the empty seats based on a randomly generated seat number. If the seat is not empty, then the program should continue to search for other empty seats.
This is what I have:
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <string>
using namespace std;
enum pax {E, M, F, C};
pax seats[50] = {E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E,
E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E, E};
int paxNumMaleTotal; // Total number of Male passengers Loaded
int paxNumFemaleTotal;
int paxNumChildTotal;
void random(int j);
int main() {
// Randomize seating for Male
int n=1;
int i=0;
paxNumMaleTotal=35;
paxNumFemaleTotal=8;
paxNumChildTotal=5;
while (n<= paxNumMaleTotal) { // loop until all men take their seats
while (seats[i] != M || seats[i] != F || seats[i] != C) {
// take a seat unless the seat is not occupied
random(i); // generate a random seat to be taken
seats[i] = M; // Seat is taken by a man
}
n++; // seat is taken, take the next one
}
for (int k=0; k<50; k++) { // printing the seating chart
cout << seats[k] << endl;
}
}
void random(int j) // this is the function that gives a random seat number
{
srand( time( NULL ) );
j = rand() % 50;
}
So, I tried all possible options. It either puts men in all 50 seats or, like in this case, put a man in the first seat with no loop. Thanks a lot for your time!
Thanks for your help. Using the reference, I solved the issue of randomly selecting a seat. A problem with the loop is still here. It selects only one seat (randomly) and not 35 seats. :-(
EDIT: Thank you! The random_shuffle function did the trick!
for (int i=0; i < paxNumMaleTotal; i++) {
seats[i] = M;
}
for (int i = paxNumMaleTotal; i < paxNumFemaleTotal + paxNumMaleTotal; i++) {
seats[i] = F;
}
for (int i=paxNumFemaleTotal + paxNumMaleTotal; i < paxNumFemaleTotal + paxNumMaleTotal +
paxNumChildTotal; i++) {
seats[i] = C;
}
// Randomize seating for passengers
std::random_shuffle (&seats[0], &seats[49]);
This:
srand( time( NULL ) );
j = rand() % 50;
is the problem. time(NULL) has 1 second resolution. This seeds your random generator to almost always the same value, because the outer loop is much faster than one second.
Solution: Initialize your random generator only once at the beginning of the program.
Additionally: your assignement to j has no effect. You modify a copy of the argument and this copy is never returned.
Your random() function does not return anything. You probably meant passing j by reference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With