2

I am trying to make an array that has different values in its cells, but for some reason it has repeating values. Where am I going wrong?

Here is my code:

package oefarray;

public class OefArray {

    int[] getallenArray,differentArray;

    public static void main(String[] args) {
        OefArray arr = new OefArray();
        arr.differentArray(10,10);

    }

    public void differentArray(int n, int max) {
        differentArray= new int[n];
        for (int i = 0; i < differentArray.length; i++) {
            int value = (int) (Math.random() * max);
            differentArray[i]= value;
            for (int p: differentArray){
                while (value == p){
                    value = (int) (Math.random() * max);
                }
            }
            differentArray[i]= value;
            System.out.println(differentArray[i]);
        }
    }
}
4

2 回答 2

2

您没有检查新生成的值是否存在于数组中的任何位置,只是它的值不等于您正在检查的当前值。

differentArray= new int[n];
for (int i = 0; i < differentArray.length; i++) {
    int value = 0;
    while(true){
        value = (int)(Math.random()*max);
        boolean found = false;
        for(int p: differentArray){
            if(p==value){
                found = true;
                break;
            }
        }
        if(!found) break;
    }
    differentArray[i] = value;
}

这是 arshajii 解决方案的替代方案,不需要直接引用ArrayList. 正如他所指出的,这并不比他的解决方案更有效。如果您对 Lists 还不满意,这只是另一种编写方式。

int[] nums = new int[max];
for (int i = 0; i < max; i++)
    nums[i] = i;
Collections.shuffle(Arrays.asList(nums));
for (int i = 0; i < n; i++)
    differentArray[i] = nums.get(i);
于 2013-08-08T14:57:29.860 回答
0

对于使用 Java 8 的未来方法,使用IntStream.generate可以产生一些非常简洁的结果。这可能在与先前答案相同的性能窗口中执行,因此我不断言这是更有效的。然而,它更具表现力。

public int[] differentArray(int length, int maxValue) {
    if(length > maxValue) {
        throw new IllegalArgumentException("The number of possible unique values is smaller than available number of slots for them.");
    }
    final Random random = new Random();
    return IntStream.generate(() -> random.nextInt(maxValue))
                    .distinct()
                    .limit(length)
                    .toArray();
}
于 2016-03-15T21:48:20.763 回答