samedi 25 juin 2022

C++ generating distinct random numbers (infinite loop problem)

I am trying to generate 5 distinct numbers in the range 1 to 9 (inclusive). I am still learning c++ so i only know this "method" for generating random numbers and i am not familiar with the latest features of the language. This is what i tried :

#include <iostream>
#include <ctime>
#include <cstdlib>

void Generate(int arr[], const int size){
    std::srand(std::time(0));
    arr[0] = 1 + (std::rand() / ((1u + RAND_MAX) / 8));
    int random;
    int counter;
    bool flag;
    for(int i = 1; i < size; ++i){
        counter = 0;
        flag = true;
        while(flag){
        random = 1 + (std::rand() / ((1u + RAND_MAX) / 8));
        for(int j = 0; j < i; ++j){
            if(arr[j] == random){
                ++counter;
            }
        }
        if(!counter){
            arr[i] = random;
            flag = false;
        }
        else{
            std::cout << "false ";
        }
    }
    }
}

void Print(int const arr[], const int size){
    for(int i = 0; i < size; ++i){
        std::cout << arr[i] << ' ';
    }
}

int main() {

    constexpr int ksize = 5;
    int arr[ksize];
    Generate(arr, ksize);
    Print(arr, ksize);

    return 0;
}

This works fine sometimes, but on many occasions it gives an infinite loop. Why ?

By the way, i added:

else{
std::cout << "false ";
}

to the code just to make sure that i was getting an infinite loop.




Aucun commentaire:

Enregistrer un commentaire