0

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.

Ken Za
  • 81
  • 6
  • First of all C++ have very good [PRGN functions and classes](https://en.cppreference.com/w/cpp/numeric/random) that you should use rather than `srand` and `rand`. Secondly, use a [`std::unordered_set`](https://en.cppreference.com/w/cpp/container/unordered_set) to store the numbers, and simply insert into the set in a loop until the set is the required size. – Some programmer dude Jun 25 '22 at 17:32
  • 3
    @Someprogrammerdude Or start with a `vector` containing 1 to 9, [std::shuffle](https://en.cppreference.com/w/cpp/algorithm/random_shuffle) it, and grab the first five numbers from it. – Nathan Pierson Jun 25 '22 at 17:33
  • As for your current code, this seems like a very good time to learn how to [*debug*](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) your programs, and how to use a [*debugger*](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) to step through the code statement by statement while monitoring variables and their values. – Some programmer dude Jun 25 '22 at 17:34
  • @NathanPierson thanks, this is nice. But since i do not know vectors and `std::shuffle`yet, i guess i can make an array instead, generate random numbers for the positions and swap the values – Ken Za Jun 25 '22 at 17:55
  • 1
    It would probably be easier to understand the problem if the code was properly indented. Especially, you should indent the while loop. – jpmarinier Jun 25 '22 at 22:17

0 Answers0