3

I need to find a way to fill an array with random numbers without having duplicates,so i wrote this code and it works.My question is,is this code efficient and will it really have no duplicates? Thanks in advance!

#include <iostream>
#include <time.h>
#include <stdlib.h>

int main(void) {
    srand(time(NULL));
    std::size_t array_size=100;
    int array[array_size];
    for(int i=0;i<array_size;i++) {
        array[i]=rand()%105+1;
            for(int k=0;k<array_size;k++) {         // Checks if there is a duplicate in the array //
                    if(i!=k) {                      // Don't check for the same array position //
                        if(array[i]==array[k]) {    // If a duplicate is found,repeat the check process//
                        array[i]=rand()%105+1;
                        k=-1;                       // -1 so the for loop starts from zero //
                }
            }
        }
    }
    return 0;
}
7
  • Do these numbers need to be in a certain range? Commented Mar 17, 2020 at 15:52
  • Prefer <random> in C++. Commented Mar 17, 2020 at 15:52
  • 1
    Use a shuffle instead. Plenty of ways to do that with the C++11 standard library. Commented Mar 17, 2020 at 15:53
  • No need to be in certain range,had to set it manually so i can check if there are duplicates in the output file. Commented Mar 17, 2020 at 15:54
  • You don't need to pass void as function argument in C++ . Commented Mar 17, 2020 at 15:57

1 Answer 1

6

That approach works fine when the number of desired values is much less than the number of possible values. Most of time it won't produce a duplicate value, so it just keeps the one it produced. But when there isn't a lot of slack there are lots of duplicates; when this code gets close to the end it's generating a value between 1 and 106 when there are only six or seven or so acceptable values. So it ends up spinning its wheels.

Instead of doing all that looping, create an array that holds all of the possible values, randomly shuffle it, and throw out the extra ones:

int array[105];
for (int i = 0; i < 105; ++i)
    array[i] = i + 1;
std::mt19937_64 mt;
std::shuffle(std::begin(array), std::end(array), mt);
for (int i = 0; i < 100; ++i)
    std::cout << array[i] << '\n';
Sign up to request clarification or add additional context in comments.

3 Comments

Instead of those ugly for (int i= ... you could use a range based for.
Why not std::iota(std::begin(array), std::end(array), 1);?
The point is to illustrate the underlying principle. You guys can write it however you like. <g>

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.