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

问题描述 投票:-3回答:1

我想生成两个随机的整数对,在长度为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;
}

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

java random
1个回答
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循环可能不会停止,例如当非常不幸或给定的参数相矛盾时。如果这是一个问题,你可以计算不成功的尝试次数,并在超过定义的尝试上限时中止。


您需要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}生成16个不同的数字,只有9个数字。另请注意,当两个参数都接近时,使用另一种预先定义{0, 1, 2, 3, 4, 5, 6, 7, 8}的方法将会非常快,现在只需置换此集合然后迭代它,如Collections.shuffle(numbers)然后for(Integer number : numbers) { ... }

© www.soinside.com 2019 - 2024. All rights reserved.