In: Computer Science
How to make a random word generator from a list of array?
string word ={ "RD","BL", "YW", "GR","OR","VL","WH","BL" }
The output should produce 4 random words from the list like;
Expected output: RD YW OR BL
CODE USED: C++
Leave Comments for any doubt.
Code:
#include <iostream>
using namespace std;
// Generating random numbers array so that wordds are non
repeating.
void generateSetOfNumbers(string str[], int n)
{
int *p = new int[n];
for (int i=0; i<n; ++i)
p[i] = i;
//shuffle p
for (int i=n-1; i>0; --i)
{
//get swap index
int j = rand()%i;
//swap p[i] with p[j]
int temp = p[i];
p[i] = p[j];
p[j] = temp;
}
/*Change value below if you want to generate more words from the
list,
right now it is generating 4 word, make it 5 if you want 5
words.
CAUTION: Do not increase the value more than size of array.
*/
for (int i=0; i<4; ++i)
cout << str[p[i]]<<" ";
}
int main() {
string word[] ={ "RD","BL", "YW", "GR","OR","VL","WH","BL" };
// Getting size of array
int size = sizeof(word)/sizeof(word[0]);
generateSetOfNumbers(word, size);
return 0;
}
Output Screenshot: