Reputation: 1
Here is my code for a simple game. paste it and try it.
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
int main (void)
{
string g[4],
b[4],
a[4],
l[4];
srand((unsigned int)time(0));
cout << "Welcome!\n\n";
cout << "Type 4 girl names.\n";
for (int gi = 0; gi < 4; gi++)
cin >> g[gi];
cout << "Type 4 boy names.\n";
for (int bi = 0; bi < 4; bi++)
cin >> b[bi];
cout << "\nWhat they do (enter 4 actions)?\n";
for (int ai = 0; ai < 4; ai++)
getline(cin, a[ai]);
cout << "\nWhere is happening (enter 4 locations)?\n";
for (int li = 0; li < 4; li++)
getline(cin, l[li]);
for (int c = 0; c < 4; c++)
cout << g[rand() % 4] << " and " << b[rand() % 4] << " are " << a[rand() % 4] << " from a " << l[rand() % 4] << endl;
return (0);
}
At the end in the 4 lines some of the names, actions and locations repeat. How do I make them to not repeat and use every name that you will enter?
Upvotes: 0
Views: 793
Reputation: 385144
for (int c = 0; c < 4; c++)
cout << g[rand() % 4] << " and " << b[rand() % 4] << " are "
<< a[rand() % 4] << " from a " << l[rand() % 4] << endl;
You've made an assumption that consecutive calls to rand()
are guaranteed to not yield the same result as previous calls to rand()
, but this is baseless.
Thus, there is always a possibility that you will get repeats; in fact, there is a 1 in 64 chance that you will get the same answer each time.
Either remove the randomness, or perform a random array shuffle before the loop (as demonstrated by Mr @Eladidan). Or, create an array of the numbers 0,1,2,3
, shuffle that, then use it as indexes into your data arrays.
It's the nature of random shuffling (rather than random extraction) that'll give you a non-repeating answer.
Upvotes: 0
Reputation: 2644
Use std::random_shuffle
:
std::random_shuffle(g, g + 4);
std::random_shuffle(b, b + 4);
std::random_shuffle(a, a + 4);
std::random_shuffle(l, l + 4);
And then just iterate over all of the shuffled arrays:
for (int c = 0; c < 4; c++)
cout << g[c] << " and " << b[c] << " are " << a[c] << " from a " << l[c] << endl;
Upvotes: 1