我遇到了一个我原本认为很容易解决的问题!
我有一个包含 4 个值(空、男性、女性、儿童)的枚举。我有一个对应于 50 个座位的数组。所以,我想根据随机生成的座位号将男人、女人和儿童放在空座位上。如果座位不是空的,那么程序应该继续搜索其他空座位。
这就是我所拥有的:
#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;
}
所以,我尝试了所有可能的选择。它要么让男性坐在所有 50 个座位上,要么像在这种情况下,把一个男人放在第一个座位上,没有环。非常感谢您的时间!
谢谢你的帮助。使用参考,我解决了随机选择座位的问题。循环的问题仍然存在。它只选择一个席位(随机)而不是 35 个席位。:-(
编辑:谢谢!random_shuffle 函数成功了!
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]);