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? Mar 17, 2020 at 15:52
  • Prefer <random> in C++.
    – sweenish
    Mar 17, 2020 at 15:52
  • 1
    Use a shuffle instead. Plenty of ways to do that with the C++11 standard library.
    – Bathsheba
    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.
    – Exxon
    Mar 17, 2020 at 15:54
  • You don't need to pass void as function argument in C++ . Mar 17, 2020 at 15:57

1 Answer 1

7

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';
3
  • 1
    Instead of those ugly for (int i= ... you could use a range based for. Mar 17, 2020 at 15:59
  • 1
    Why not std::iota(std::begin(array), std::end(array), 1);?
    – Evg
    Mar 17, 2020 at 16:00
  • The point is to illustrate the underlying principle. You guys can write it however you like. <g> Mar 17, 2020 at 17:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.