我正在尝试生成一个随机的、不重复的三位或四位数字。

3
我正在尝试在Java中生成一个随机的、不重复的3或4位数字,但不能使用循环、数组或方法(除了内置的用于生成随机数的Math.random()方法),只能使用基本的语句如if语句。
我尝试了以下代码: (int)(Math.random()*9899+100);
但它只返回4位不同的数字。这里的“distinct”指的是,没有任何数字应该重复出现。例如,232、7277、889、191等数字不允许存在。但像1234、3456、8976、435这样的数字是不同的,是允许的。

2
“distinct” 是什么意思?是指数字都不相同吗? - Andy Turner
1
不使用循环、数组或方法,这是一个相当大的要求。 - Andy Turner
1
这个回答解决了你的问题吗?如何生成不同数字的随机数 - Peter O.
2
“不使用循环、数组或方法” - random() 是一种方法。除此之外,您在这个上下文中所说的“distinct”或“indistinct”是什么意思?您能提供一个样本输出,并描述它与您期望的有何不同吗? - David
感谢@MuntasirAonik提供的答案,但它既不符合“独特”要求,也不符合“3或4位数”的要求。 - Andy Turner
显示剩余8条评论
1个回答

1
以下内容并不会生成公平的数字,但可以生成任何4位数,3位数中不会有0。
// 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);

你可以将新数字加上自身,而不是加一,以获得更均匀的分布,这需要处理一些特殊情况。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接