简体   繁体   中英

I'm trying to generate a random distinct 3 or 4 digit number

I'm trying to generate a random distinct 3 or 4 digit number in Java, without using loops, arrays, or methods( except the in built math random method for generating random numbers), just the basic stuff like if statements.

I tried

(int)(Math.random()*9899+100);

But it's only returning 4 digit indistinct numbers. By distinct I mean, no number should repeat itself. Numbers like 232, 7277, 889, 191 aren't allowed. But numbers like 1234, 3456, 8976, 435 are distinct and allowed

The following is not going to generate the numbers fairly but any 4 digit number can be generated, 3 digit numbers are not going to have 0 in them.

// first digit between 0 and 9, if it's 0 we will have a 3 digit number
int first = (int)(Math.random() * 10);  

int second = (int)(Math.random() * 10);
// if it's the same as the first add one to it, use modulo to wrap around
if (first == second)
    second = (second + 1) % 10;

// the same as with second digit just with more checks
int third = (int)(Math.random() * 10);
if (third == first || third == second)
    third = (third + 1) % 10;
// if it's still the same, add one once more, after doing it a second time new digit is guaranteed 
if (third == first || third == second)
    third = (third + 1) % 10;

// the same as with second digit just with more checks
int fourth = (int)(Math.random() * 10);
if (fourth == first || fourth == second || fourth == third)
    fourth = (fourth + 1) % 10;
if (fourth == first || fourth == second || fourth == third)
    fourth = (fourth + 1) % 10;
if (fourth == first || fourth == second || fourth == third)
    fourth = (fourth + 1) % 10;

System.out.println(1000 * first + 100 * second + 10 * third + fourth);

You can add the new digit to itself instead of adding one to have a more uniform distribution, it requires handling of some corner cases.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM