Remove Duplicates from Array

I'm trying to create a random number generator and storing it into an array, however I sometimes get duplicates. How do I remove the duplicate from the array and generate a unique number on each run?

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
#include <iostream>
#include <stdlib.h>
#include <time.h>
#include <string>
#include <limits>

using namespace std;

int main (){

    string Retry;
    int num[5];
    srand(time(NULL));

    cout << "Welcome to the Number Generator.\n" << endl;
    cout << "Press ENTER to generate numbers.";
    cin.ignore(numeric_limits<streamsize>::max(),'\n');
    cout << endl;


    do{

    cout << "Your numbers are: ";

    for (int i=0;i<5;i++){
        num[i]=0;
        num[i]+=rand()%50+1;

        cout << num[i] << " ";

    }

    cout << endl;
    cout << "\nGenerate more numbers? [Y/N]: ";
    cin >> Retry;
    cout << endl;

} while (Retry == "Y" || Retry =="y");

return 0;

}
You'd need to, after generating a particular index's number, check all previously generated numbers for any matches. Probably a more efficient way to do this, but here's code that would probably work:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
for (int i = 0; i < 5; i++)
{
    bool isDuplicate;
    //generate this number at least once
    do {
        //generate intial number
        num[i] = rand()%50 + 1;

        //assume number is unique
        isDuplicate = false;

        //find case among previously generated numbers where there is a duplicate
        for (int j = 0; j < i; ++j)
        {
            if ( num[i] == num[j] )
            {
                isDuplicate = true;
                break;
            }
        }
    } while ( isDuplicate );
}
Topic archived. No new replies allowed.