使用java创建一个4位随机数,数字不重复

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18317298/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:26:08  来源:igfitidea点击:

Creating a 4 digit Random Number using java with no repetition in digits

javarandomnumbers

提问by kakabali

I wrote a code using java to create a random 4 digit number with no repetition of digits, the code I wrote is given below :-

我使用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);


here are the test cases(generated from System.out.println(R1+""+R2+""+R3+""+R4);) are as following :-


这里是测试用例(生成自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


Now My question here is, that if there is some better way to do this. If I could enhance it in some way?


现在我的问题是,如果有更好的方法来做到这一点。如果我可以以某种方式增强它?

采纳答案by Jeroen Vannevel

Create a list of integers from 0 to 9, shuffle it and extract the first 4.

创建一个从 0 到 9 的整数列表,将其打乱并提取前 4 个。

public static void main(String[] args) {
    List<Integer> numbers = new ArrayList<>();
    for(int i = 0; i < 10; i++){
        numbers.add(i);
    }

    Collections.shuffle(numbers);

    String result = "";
    for(int i = 0; i < 4; i++){
        result += numbers.get(i).toString();
    }
    System.out.println(result);
}

There's some ugly string-to-int conversing going on, but you get the idea. Depending on your use case you can see what is needed.

有一些丑陋的 string-to-int 对话正在进行,但你明白了。根据您的用例,您可以看到需要什么。

回答by fred02138

Use a Set maybe?

可能使用 Set 吗?

Random r = new Random();
Set<Integer> s = new HashSet<Integer>();
while (s.size() < 4) {
    s.add(r.nextInt(9));
}

回答by Rob

A couple of approaches:

几种方法:

  1. Use a Set to hold the digits and keep adding random digits until the set has four values in it.

  2. Create an array with values 0-9 in it. Shuffle the array and take the first four values.

  1. 使用 Set 来保存数字并不断添加随机数字,直到该集合中有四个值。

  2. 创建一个包含 0-9 值的数组。随机排列数组并取前四个值。

If performance matters, you will want to try a couple of different methods and see which is faster.

如果性能很重要,您将需要尝试几种不同的方法,看看哪种方法更快。

回答by Algiz

Create a list with Integer from 0 to 9 (so 10 items in total)

创建一个从 0 到 9 的整数列表(总共 10 个项目)

List<Integer> l = ...
Collections.shuffle(l);
d1 = l.get(0);
d2 = l.get(1);
d3 = l.get(2);
d4 = l.get(3);

回答by Juvanis

Here is my solution without using any additional data structure, looping on generating random number till it has unique digits.

这是我的解决方案,不使用任何额外的数据结构,循环生成随机数,直到它具有唯一的数字。

int a = 0, b = 0, c = 0, d = 0;
int x = 0;
while (true) {
    x = r.nextInt(9000) + 1000;
    a = x % 10;
    b = (x / 10) % 10;
    c = (x / 100) % 10;
    d = x / 1000;
    if (a == b || a == c || a == d || b == c || b == d || c == d)
        continue;
    else
        break;
}

System.out.println(x);

回答by MZ4Code

Here's my approach, even though it uses a lot of string parsing but no data structure:

这是我的方法,即使它使用了大量字符串解析但没有数据结构:

 static int generateNumber(int length){
            String result = "";
            int random;
            while(true){
                random  = (int) ((Math.random() * (10 )));
                if(result.length() == 0 && random == 0){//when parsed this insures that the number doesn't start with 0
                    random+=1;
                    result+=random;
                }
                else if(!result.contains(Integer.toString(random))){//if my result doesn't contain the new generated digit then I add it to the result
                    result+=Integer.toString(random);
                }
                if(result.length()>=length){//when i reach the number of digits desired i break out of the loop and return the final result
                    break;
                }
            }

            return Integer.parseInt(result);
        }

回答by Hot Licks

Roughly (not tested):

粗略(未测试):

int randomNum = r.nextInt(5040);
int firstDigit = randomNum % 10;
randomNum = randomNum / 10;
int secondDigit = randomNum % 9;
randomNum = randomNum / 9;
int thirdDigit = randomNum % 8;
randomNum = randomNum / 8;
int fourthDigit = randomNum % 7;

if (secondDigit == firstDigit) {
  secondDigit++;
}

while ((thirdDigit == firstDigit) || (thirdDigit == secondDigit)) {
  thirdDigit++:
}

while ((fourthDigit == firstDigit) || (fourthDigit == secondDigit) || (fourthDigit == thirdDigit)) {
  fourthDigit++;
}

(After coding this I realized that the increment operations need to be done modulo 10.)

(编码后,我意识到增量操作需要以 10 为模进行。)