Checking for duplicate values in an array


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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48

#include<iostream>
#include<cstdlib>
#include<ctime>
#include<cstring>
#include<conio.h>
using namespace std;

int main(){
	
	const int 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();
}
Last edited on
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.
Last edited on
Topic archived. No new replies allowed.