我使用java编写了一个代码来创建一个没有重复数字的随机4位数字,我编写的代码如下:-
Random r = new Random();
d1 = r.nextInt(9);
d2 = r.nextInt(9);
d3 = r.nextInt(9);
d4 = r.nextInt(9);
while(d1==d2||d1==d3||d1==d4||d2==d3||d2==d4||d3==d4)
{
if(d1==d2||d2==d3||d2==d4)
{
d2 = r.nextInt(9);
}
if(d1==d3||d2==d3||d3==d4)
{
d3 = r.nextInt(9);
}
if(d1==d4||d2==d4||d3==d4)
{
d4 = r.nextInt(9);
}
}
System.out.println(d1+""+d2+""+d3+""+d4);
以下是测试用例(从 生成System.out.println(R1+""+R2+""+R3+""+R4);
)如下:-
0123 | OK as required
1234 | OK as required
2123 | not OK because 2 is present more than one time
9870 | OK as required
0444 | not OK because 4 is present more than one time
现在我的问题是,如果有更好的方法来做到这一点。如果我能以某种方式增强它?