Hello everyone. I am currently in the process of creating my first C++ project, involving a set of different arrays. I am struggling to process the code, because some of the text within certain arrays are the same (different index). I created a sample code to diagnose the issue. For example, if you replace bar in a[6] with foo, that means two indexes will have foo, and therefore the program will run unsuccessfully. Any help with this would be greatly appreciated. Thanks.
What is the actual goal? "print random non-duplicate words/numbers/whatever"?
std::string book[6] {"bar", "bar", "corge", "bar", "waldo", "quux"};
The book has 6 words, but only 4 unique words. It is not possible to get unique 6 words from that book.
If you pick a random word and you have already seen it before, you don't know whether you have picked the same word again or picked a duplicate.
Can you copy only unique words from the book to a second array first?
Both arrays must have same size (like your a and b) for all words could be unique, but you need to keep count of words that you add to the second array. There is nothing random in that copy operation.
Then you can print the words of the second array in random order.
#include <iostream>
#include <string> // <==== better to use
#include <cstdlib> // <==== use modern headers
#include <ctime> // <==== use modern headers
usingnamespace std;
int main()
{
srand( time( 0 ) );
//string a[6] = {"foo", "bar", "corge", "thud", "waldo", "quux"};
string a[6] = {"foo", "foo", "corge", "thud", "waldo", "quux"};
string b[6];
int index[6]; // shuffle the INDICES, not the values
index[0] = rand() % 6; // first index
for ( int i = 1; i < 6; i++ )
{
bool repeat = true; // force it to loop at least once
while( repeat ) // repeat until you get one that hasn't been used before
{
index[i] = rand() % 6;
repeat = false; // nothing matched yet
for ( int j = 0; j < i; j++ )
{
if ( index[j] == index[i] )
{
repeat = true;
break;
}
}
}
}
for( int k = 0; k < 6; k++ )
{
b[k] = a[ index[k] ];
cout << b[k] << " ";
}
}
However, there are many other ways of doing this that would avoid about half of your rand() calls being wasted.