Java:用随机整数创建数组(整数只能使用一次)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7940439/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 22:06:35  来源:igfitidea点击:

Java: create array with random int's (int's can only be used once)

javaalgorithmrandomsorting

提问by gieldops

I have an array called arr, with place for 15 elements. I need to place the numbers 1 through 15 in a random order into that array. Here is what I have tried:

我有一个名为 的数组arr,可容纳 15 个元素。我需要将数字 1 到 15 以随机顺序放入该数组中。这是我尝试过的:

int[] arr = new int[15];
int i,j,k,n;

for (i = 0; i<15; i++) {
    for (j=0; j<15; j++) {
        n = (int)(Math.random() * 14 + 1);
        if (rij[j] != n) {
            rij[i] = n;
            break;
        }
    }
}

Thanks! :)

谢谢!:)

回答by Marcelo

Use an ArrayListand fill it up with numbers 1 to 15.

使用一个ArrayList并用数字 1 到 15 填充它。

Shufflethe list.

随机播放列表。

Convert it to an array.

将其转换为数组

回答by Brian Roach

This seems like homework (or an interview question?). If that's the case and you are required to use arrays rather than the built in methods with the Java Collection Objects, (or even if not, really), the answer is the Fisher-Yates Shuffle algorithm

这似乎是家庭作业(或面试问题?)。如果是这种情况并且您需要使用数组而不是 Java 集合对象的内置方法(或者即使不是,真的),答案是Fisher-Yates Shuffle 算法

The modern in-place shuffle is:

现代就地洗牌是:

To shuffle an array a of n elements (indexes 0..n-1):
for i from n ? 1 downto 1 do
   j ← random integer with 0 ≤ j ≤ i
   exchange a[j] and a[i]

(I'd have to check, but I suspect this is what Java uses under the hood for its shuffle()methods).

(我必须检查一下,但我怀疑这是 Java 在其shuffle()方法的幕后使用的内容)。

Edit because it's fun to implement algorithms:

编辑,因为实现算法很有趣:

In java, this would be:

在java中,这将是:

public static void main(String[] args) {

    int[] a = new int[15];
    for (int i = 1; i <= 15; i++)
    {
        a[i-1] = i;
    }

    Random rg = new Random();
    int tmp;
    for (int i = 14; i > 0; i--)
    {
        int r = rg.nextInt(i+1);
        tmp = a[r];
        a[r] = a[i];
        a[i] = tmp;
    }

    for (int i = 0; i < 15; i++)
        System.out.print(a[i] + " ");

    System.out.println();


}

And ... this can be further optimized using the inside-out version of the algo since you're wanting to insert a known series of numbers in random order. The following is the best way to achieve what you stated as wanting to do as there are no extra copies being made such as when creating an ArrayListand having it copy back out to an array.

并且...这可以使用算法的由内向外版本进一步优化,因为您想以随机顺序插入一系列已知的数字。以下是实现您所说的想要做的事情的最佳方法,因为没有额外的副本,例如在创建一个ArrayList并将其复制回数组时

a = new int[15];
Random rg = new Random();
for (int i = 0; i < 15; i++)
{
    int r = rg.nextInt(i+1);
    a[i] = a[r];
    a[r] = i+1;
}

回答by Lukas Eder

Do it like this

像这样做

// Create an ordered list
List<Integer> list = new ArrayList<Integer>();
for (int i = 1; i < 16; i++) {
    list.add(i);
}

// Shuffle it
Collections.shuffle(list);

// Get an Integer[] array
Integer[] array1 = list.toArray(new Integer[list.size()]);

// Get an int[] array
int[] array2 = new int[list.size()];
for (int i = 0; i < list.size(); i++) {
    array2[i] = list.get(i);
}

回答by óscar López

This will leave the elements randomly shuffled in a Integer[], if that's fine with you:

这将使元素在 a 中随机混洗Integer[],如果这对您没问题:

List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 15; i++)
    list.add(i + 1);

Collections.shuffle(list);
Integer[] arr = list.toArray(new Integer[0]);

回答by Marcx

I will do something like this:

我会做这样的事情:

First create a temporary arraylist filled with numbers from start to end, then using random select a number, copy it into array and remove it from the temp arraylist, repeat until the arraylist is empty...

首先创建一个从头到尾填充数字的临时数组列表,然后使用随机选择一个数字,将其复制到数组中并将其从临时数组列表中删除,重复直到数组列表为空...

    ArrayList<Integer> arr = new ArrayList<Integer>();
    int[] arr2 = new int[15];
    int i,j,k,n;

    for (i=0;i<15;i++) arr.add(i+1);
    i=0;
    while(arr.size()>0){                    
         n = (int)(Math.random() * (14 + 1 - i));
         arr2[i]=arr.get(n);
         arr.remove(n);
         i++;
    }