jeudi 2 septembre 2021

Is there a better algorithm than this for creating an array of 5 unique integers between 1 and 20 in C++?

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.




Aucun commentaire:

Enregistrer un commentaire