0

For my programm, I need four random single-digit integers that are not the same.

Meaning: i.e. 1568 is valid, 1251 is not.

I found a pretty straightforward way to achieve this by checking wether the digits are equal to an earlier generated integer and if so, generating a new one.

srand(time(NULL));

int dig1 = rand() % 10;

int dig2 = rand() % 10;
while (dig2 == dig1)
{
    dig2 = rand() % 10;
}

int dig3 = rand() % 10;
while (dig3 == dig1 || dig3 == dig2)
{
    dig2 = rand() % 10;
}

int dig4 = rand() % 10;
while (dig4 == dig1 || dig4 == dig2 || dig4 == dig3)
{
    dig2 = rand() % 10;
}

Is there a more elegant way to code this? Thank you for your help and have a nice day!

Moritz L.
  • 177
  • 1
  • 2
  • 10

0 Answers0