Java中没有重复的随机数

时间:2019-05-03 11:05:43

标签: java random

我喜欢它:

    int randOne = 3;
    int randTwo = 4;
    int oneNubmer;
    int twoNumber;

    do {
         oneNubmer = 1 + (int) (Math.random() * randOne);
         twoNumber = 1 + (int) (Math.random() * randTwo);
    } while (oneNubmer == twoNumber);

它可以工作,但是大大增加了操作时间,因为此功能被称为1000倍以上。

如何做得更好?

1 个答案:

答案 0 :(得分:2)

一旦您对要生成的数字强加某些规则(例如,它们不能重复),就不能再将它们视为随机数了。

您可以考虑将oneNumber添加到twoNumber(或在twoNumber的计算中使用oneNumber的任何其他操作),这样它们将永远不会相等。尽管这再次强加了事实,那就是twoNumber总是会比oneNumber高,因此也可以再次被视为“随机”概念的违反。

oneNumber = 1 + (int) (Math.random() * randOne);
twoNumber = 1 + oneNumber + (int) (Math.random() * randTwo);

对于需要生成1-4之间的第一个数字和1-5之间的第二个数字而不重复的要求,可以使用以下方法:

// Create a list containing numbers 1 till 5
List<Integer> numbers = new ArrayList<Integer>();
for(int i = 1; i < 6; i++) {
  numbers.add(i);
}

Random random = new Random();

// Randomly get the index of your first number, this will be a number 
// between 1 and 4
int firstIndex = random.nextInt(4);
int number1 = numbers.get(firstIndex);

// Remove that number from the list, your list now becomes size 4, and no 
// longer contains the first number you picked.
numbers.remove(firstIndex);

// Randomly get the index of your second number, this will be a number 
// between 1 and 5 without the number picked earlier.
int secondIndex = random.nextInt(4);
int number2 = numbers.get(secondIndex);

System.out.println(number1);
System.out.println(number2);

也许更干净,更快:

// Create a list containing numbers 1 till 5 -> might want to extract this
// from the method so you don't have to rebuild the array over and over 
// again each call...
List<Integer> numbers = new ArrayList<Integer>();
for(int i = 1; i < 6; i++) {
  numbers.add(i);
}

// Shuffle the array randomly
Collections.shuffle(numbers);

// Get the first 2 numbers from the array
int number1 = numbers.get(0);
int number2 = numbers.get(1);

// If number1 equals 5, swap number1 and number2 as you want number1 to be 
// 1-4 and number2 to be 1-5
if(number1 == 5) {
  number1 = number2;
  number2 = 5;
}

System.out.println(number1);
System.out.println(number2);