2

I need to generate random non repeating number array in C++, in this part of code I generate random numbers using, srand function, but some of the numbers are repeating. The main task is to generate random numbers for lottery ticket, so I need to generate numbers until golden number which is marked as int golden.

#include <cstdlib>
#include <ctime>
#include <iostream>

using namespace std;

int main()
{
  int golden = 31;
  int i = 0;
  int array[35];

 srand((unsigned)time(0));
    while(i != golden){
        array[i] = (rand()%75)+1;
        cout << array[i] << endl;
        i++;
}
 }
user3476593
  • 23
  • 1
  • 5
  • related : http://stackoverflow.com/questions/21948091/how-to-generate-an-array-of-256-distinct-numbers/21950195 – uchar Sep 16 '14 at 21:14
  • Related: https://stackoverflow.com/questions/22842289 https://stackoverflow.com/questions/9755538 [python using built-in] https://stackoverflow.com/questions/14473321 https://stackoverflow.com/questions/196017 – user202729 Apr 11 '18 at 08:24

2 Answers2

7

One strategy is to populate an array with numbers from 1 to 75, and then use std::random_shuffle() on it. You can then read the numbers from the array until you hit the golden number.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

I had a similar task and used two functions to solve the problem of repeating numbers.

#include <iostream>
#include <ctime>

using namespace std;

void generateRandom(int array[], int length);
bool findVal(int array[], int size, int value);

int main() {
    int arraySize = 10;
    int array[arraySize];

    generateRandom(array, arraySize);
    for (auto i : array) {
        cout << i << " ";
    }

    return 0;
}

void generateRandom(int array[], int length) {
    srand((int) time(nullptr));
    int temp;

    for (int i = 0; i < length; ++i) {
        temp = rand() % 20 + 1;
        if (findVal(array, i, temp)) {
            i--;
            continue;
        } else {
            array[i] = temp;
        }
    }
}

bool findVal(int *array, int size, int value) {
    for (int i = 0; i < size; ++i) {
        if (array[i] == value) {
            return true;
        }
    }
    return false;
}

Within the generateRandom function, you can switch the 20 and 1 used in the for loop with your preferred upper and lower limits respectively.