Algorithm for creating an array of 5 unique integers between 1 and 20 [duplicate]

  array-algorithms, c++, performance, random

My goal is creating an array of 5 unique integers between 1 and 20. Is there a better algorithm than what I use below?

It works and I think it has a constant time complexity due to the loops not being dependent on variable inputs, but I want to find out if there is a more efficient, cleaner, or simpler way to write this.

int * getRandom( ) {

  static int choices[5] = {};
  srand((unsigned)time(NULL));
   
  for (int i = 0; i < 5; i++) {

    int generated = 1 + rand() % 20;
    for (int j = 0; j < 5; j++){
      if(choices[j] == generated){
        i--;
      }
    }
    
    choices[i] = generated;
    cout << choices[i] << endl;
  }

  return choices;
}

Thank you so much for any feedback. I am new to algorithms.

Source: Windows Questions C++

LEAVE A COMMENT