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++;
}
 }
2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.