lundi 8 novembre 2021

random 4 digit number with non repeating digits in C

Im trying to make a get_random_4digit function that generates a 4 digit number that has non-repeating digits and digits ranging from 1-9 while only using int's, if, while and functions, so no arrays etc.

This is the code i have but it is not really working as intended, could anyone point me in the right direction?

int get_random_4digit() {
int d1 = rand() % 9 + 1;
int d2 = rand() % 9 + 1;

while (true) {
    if (d1 != d2) {
        int d3 = rand() % 9 + 1;
        if (d3 != d1 || d3 != d2) {
            int d4 = rand() % 9 + 1;
            if (d4 != d1 || d4 != d2 || d4 != d3) {
                random_4digit = (d1 * 1000) + (d2 * 100) + (d3 * 10) + d4;
                break;
            }
        }
    }
}
printf("Random 4digit = %d\n", random_4digit);

}




Aucun commentaire:

Enregistrer un commentaire