Java Array独特的随机生成的整数

时间:2013-11-18 02:22:03

标签: java arrays

public static int[] uniqueRandomElements (int size) {

    int[] a = new int[size];

    for (int i = 0; i < size; i++) {
        a[i] = (int)(Math.random()*10);

        for (int j = 0; j < i; j++) {
            if (a[i] == a[j]) {
                a[j] = (int)(Math.random()*10);
            }
        }   
    }

    for (int i = 0; i < a.length; i++) {
        System.out.print(a[i]+" ");
    }
    System.out.println();
    return a;
}

我上面有一个方法,它应该生成用户指定的随机元素数组。随机生成的整数应介于0和10之间(包括0和10)。我能够生成随机整数,但我遇到的问题是检查唯一性。我检查唯一性的尝试是在我上面的代码中,但数组仍然包含重复的整数。我做错了什么,有人能给我一个暗示吗?

10 个答案:

答案 0 :(得分:14)

for (int i = 0; i < size; i++) {
    a[i] = (int)(Math.random()*10);

    for (int j = 0; j < i; j++) {
        if (a[i] == a[j]) {
            a[j] = (int)(Math.random()*10); //What's this! Another random number!
        }
    }   
}

您确实找到了重复的值。但是,您可以将其替换为可能重复的另一个随机数。相反,试试这个:

for (int i = 0; i < size; i++) {
    a[i] = (int)(Math.random()*10);//note, this generates numbers from [0,9]

    for (int j = 0; j < i; j++) {
        if (a[i] == a[j]) {
            i--; //if a[i] is a duplicate of a[j], then run the outer loop on i again
            break;
        }
    }  
}

但是,这种方法效率低下。我建议制作一个数字列表,然后将其随机化:

ArrayList<Integer> a = new ArrayList<>(11);
for (int i = 0; i <= 10; i++){ //to generate from 0-10 inclusive. 
                               //For 0-9 inclusive, remove the = on the <=
    a.add(i);
}
Collections.shuffle(a);
a = a.sublist(0,4);
//turn into array

或者你可以这样做:

ArrayList<Integer> list = new ArrayList<>(11);
for (int i = 0; i <= 10; i++){
    list.add(i);
}
int[] a = new int[size];
for (int count = 0; count < size; count++){
    a[count] = list.remove((int)(Math.random() * list.size()));
}

答案 1 :(得分:1)

如果您有副本,则只重新生成一次相应的数字。但它可能会创建另一个副本。您复制的检查代码应该包含在循环中:

while (true) {
    boolean need_to_break = true;
    for (int j = 0; j < i; j++) {
        if (a[i] == a[j]) {
            need_to_break = false; // we might get another conflict
            a[j] = (int)(Math.random()*10);
        }
    }
    if (need_to_break) break;
}   

但请确保size小于10,否则您将获得无限循环。

编辑:虽然上述方法解决了问题,但效率不高,不应用于大型数组。此外,这对完成所需的迭代次数没有保证上限。

一个更好的解决方案(不幸的是只能解决第二点)可能是生成一个你想要生成的不同数字的序列(10个数字),随机置换这个序列,然后只选择第一个{{ 1}}该序列的元素并将它们复制到您的数组中。您将在时间范围内交易一些空间以获得担保。

size

或者,您可以使用相同的数字创建int max_number = 10; int[] all_numbers = new int[max_number]; for (int i = 0; i < max_number; i++) all_numbers[i] = i; /* randomly permute the sequence */ for (int i = max_number - 1; i >= 0; i--) { int j = (int)(Math.random() * i); /* pick a random number up to i */ /* interchange the last element with the picked-up index */ int tmp = all_numbers[j]; all_numbers[j] = a[i]; all_numbers[i] = tmp; } /* get the a array */ for (int i = 0; i < size; i++) a[i] = all_numbers[i]; ,而不是中间循环,您可以在其上调用ArrayList。然后你仍然需要第三个循环来将元素转换为Collections.shuffle()

答案 2 :(得分:0)

顺序数组 shuffle 开始可能会更快。然后,根据定义,它们都将唯一

查看Random shuffling of an array和Collections.shuffle函数。

int [] arr = [1,2,3,.....(size)]; //this is pseudo code

Collections.shuffle(arr);// you probably need to convert it to list first

答案 3 :(得分:0)

如果您不想为ArrayList支付额外的开销,您只需使用数组并使用Knuth shuffle

public Integer[] generateUnsortedIntegerArray(int numElements){
    // Generate an array of integers
    Integer[] randomInts = new Integer[numElements];
    for(int i = 0; i < numElements; ++i){
        randomInts[i] = i;
    }
    // Do the Knuth shuffle
    for(int i = 0; i < numElements; ++i){
        int randomIndex = (int)Math.floor(Math.random() * (i + 1));
        Integer temp = randomInts[i];
        randomInts[i] = randomInts[randomIndex];
        randomInts[randomIndex] = temp;
    }
    return randomInts;
}

上面的代码生成numElements连续的整数,而不是以统一随机的混乱顺序重复。

答案 4 :(得分:0)

 import java.util.Scanner;
 class Unique
{
public static void main(String[]args)
{
    int i,j;
    Scanner in=new Scanner(System.in);
    int[] a=new int[10];
    System.out.println("Here's a unique no.!!!!!!");
    for(i=0;i<10;i++)
    {
        a[i]=(int)(Math.random()*10);
        for(j=0;j<i;j++)
        {
            if(a[i]==a[j])
            {
                i--;

            }
        }   
    }
    for(i=0;i<10;i++)
    {
        System.out.print(a[i]);
    }
}
}

答案 5 :(得分:0)

使用集合输入您的大小并获取随机唯一数字列表。

public static ArrayList<Integer> noRepeatShuffleList(int size) {
    ArrayList<Integer> arr = new ArrayList<>();
    for (int i = 0; i < size; i++) {
        arr.add(i);
    }
    Collections.shuffle(arr);
    return arr;
}

阐述Karthik的答案。

答案 6 :(得分:0)

int[] a = new int[20];

for (int i = 0; i < size; i++) {
    a[i] = (int) (Math.random() * 20);

    for (int j = 0; j < i; j++) {
        if (a[i] == a[j]) {
            a[i] = (int) (Math.random() * 20); //What's this! Another random number!
            i--;
            break;
        }
    }
}

答案 7 :(得分:0)

    int[] a = new int [size];

    for (int i = 0; i < size; i++) 
    {
        a[i] = (int)(Math.random()*16); //numbers from 0-15
        for (int j = 0; j < i; j++) 
        {
            //Instead of the if, while verifies that all the elements are different with the help of j=0
            while (a[i] == a[j])
            {
                a[i] = (int)(Math.random()*16); //numbers from 0-15
                j=0;
            }
        }
    }

    for (int i = 0; i < a.length; i++)
    {
        System.out.println(i + ".   " + a[i]);
    }

答案 8 :(得分:0)

//Initialize array with 9 elements
int [] myArr = new int [9];
//Creating new ArrayList of size 9
//and fill it with number from 1 to 9
ArrayList<Integer> myArrayList = new ArrayList<>(9);
    for (int i = 0; i < 9; i++) {
        myArrayList.add(i + 1);
        }
//Using Collections, I shuffle my arrayList
Collections.shuffle(myArrayList);
//With for loop and method get() of ArrayList
//I fill my array
for(int i = 0; i < myArrayList.size(); i++){
    myArr[i] = myArrayList.get(i);
    }

//printing out my array
for(int i = 0; i < myArr.length; i++){
    System.out.print(myArr[i] + " ");
        }

答案 9 :(得分:0)

你可以试试这个解决方案:

public static int[] uniqueRandomElements(int size) {
    List<Integer> numbers = IntStream.rangeClosed(0, size).boxed().collect(Collectors.toList());
    return Collections.shuffle(numbers);
}