I am currently working on a program that generates a random number and storing it in an array. I first arranged it ascending order and then checks it. My problem is after checking and replacing the value, there's still the possibility that the new generated random number is the same as the previous or any other values inside the array.
#include<iostream>
#include<cstdlib>
#include<ctime>
#include<cstring>
#include<conio.h>
usingnamespace std;
int main(){
constint numWords = 3;
string pWords [4] = {"COMPUTING","TECHNOLOGY","SCIENCE"};
char guess [4]; //storage of the missing char
int index [4]; //storage of the random position
srand(time(NULL)); //choosing random word
int random = (rand() % numWords);
string choose = pWords [random];
int length = choose.length();
for(int a=0;a<4;a++){ //choosing random position
int number = (rand() % length);
index[a] = number; //storing the random position to the array
cout<<index[a]<< " ";
}
for(int b=0;b<4;b++){
for(int c=0;c<4;c++){
if(index[b]<index[c]){
int num = index [b];
index[b] = index [c];
index [c] = num;
}
}
}
cout<<"\n";
for(int d=0;d<4;d++){
for(int e=0;e<4;e++){
if(index[d]==index[e]){
int replace = rand() % length;
index [d] = replace;
}
}
}
getch();
}
This is an opportunity to expand your knowledge of the standard library. C++ comes with a number of containers; these are, as the name suggests, simply classes meant for holding things. There are various containers, and there are various helpful functions to help you do common tasks. Knowing what library facilities are available and making good use of them is a core C++ skill.
One such container is the set. It is useful in this case because the set takes care of the duplication problem for you. If you add two identical items to a set, the set only contains one of them; duplicates don't get added, with the set taking care of that for you.
Looks like you want four random numbers?
1 2 3 4 5 6
std::set<int> the_numbers; // create a set, for holding objects of type int
while (the_numbers.size() < 4) // loop until there are four different numbers in the set
{
the_numbers.insert(rand() % numWords);
}
// the_numbers now contains four different random numbers
If you have other particular needs for the numbers, then set might not be exactly the right container for you, but as you can see the code is shorter and clearer.