生成随机的不同对,没有对角线

时间:2017-07-14 09:49:27

标签: java random

我想生成两个随机的整数对,在长度为8的数组中没有重复,我不希望任何对在同一个对角线中

public static int[] randomizer(int[] v){
    int [] a= new int[8];
    for (int i = 0; i < a.length; i++) {
        a[i] = (int)(Math.random()*9);

        for (int j = 0; j < i; j++) {
            if (a[i] == a[j]) {
                i--;
                break;
            }

        }
    }
    a[0] = v[0] ;
    return a;
}

这是我到目前为止所做的。

1 个答案:

答案 0 :(得分:0)

如果我理解正确你想要生成两个整数的随机序列,每个长度 8 。这两个序列不应该有任何共同的数字,因此您需要 16个唯一随机数

接下来是对角线部分的要求 - 我没有得到它。请更准确地说明,一个小例子会很好。

同时让我们解决第一部分。生成16个唯一整数非常简单。您生成一个随机数并记住它。如果它之前已经生成,请拒绝并重试。要快速包含访问权限和添加,您应该使用HashSet。我们来看看以下代码段:

public static Set<Integer> randomUniqueNumbers(int amount, int upperBound){
    final HashSet<Integer> numbers = new HashSet<>();
    final Random rnd = new Random();

    // Stop when generated enough numbers
    while (numbers.size() < amount) {
        final int randomNumber = rnd.nextInt(upperBound);
        // Try to add it to the set.
        // The method will do nothing if the number was contained already.
        numbers.add(randomNumber);
    }

    return numbers;
}

该方法将生成金额许多唯一数字,并将其存储在Set<Integer>中,您可以通过方法进行迭代和使用。这些数字介于0包含)和upperBound独占)之间,就像您使用的(int)(Math.random() * upperBound)一样。 请注意, while-loop 可能不会停止,例如,当非常不幸或给定的参数相矛盾时。如果这是一个问题,您可以计算不成功的尝试次数,并在超出定义的尝试上限时使用中断中止。

您希望 16 这些数字,并将它们存储在两个长度为8 的数组中。以下是您如何做到这一点:

final int[] firstSequence = new int[8];
final int[] secondSequence = new int[8];

// Exchange with the correct upperBound, I assume it is 9
final Set<Integer> numbers = randomUniqueNumbers(16, 9);

Iterator<Integer> numberIter = numbers.iterator();
// Fill the first sequence
for (int i = 0; i < 8; i++) {
    firstSequence[i] = numberIter.next();
}
// Fill the second sequence
for (int i = 0; i < 8; i++) {
    secondSequence[i] = numberIter.next();
}

我认为这涵盖了大部分问题。请详细说明缺少的内容,我将更新答案。 另请注意,randomUniqueNumbers(16, 9)无法停止。它会永远运行,因为无法从{0, 1, 2, 3, 4, 5, 6, 7, 8}中生成仅 9个数字 16个不同数字。另请注意,当两个参数都接近时,使用另一种预先定义{0, 1, 2, 3, 4, 5, 6, 7, 8}的方法会非常快,现在只需置换此集合然后迭代它,如Collections.shuffle(numbers)然后{{1} }。