检索数组中的随机元素而不重复位置

时间:2014-06-15 22:46:49

标签: java arrays duplicates

我想从数组中检索元素,但是如果已经选择了元素位置,那么它就不会重复。什么是最好和/或最可读的方法呢?

我想到的方法仅适用于数字,并且当元素在另一个位置有重复时受到限制。我发现的最接近的是:Java - generate Random range of specific numbers without duplication of those numbers - how to?但它不适用,因为我不需要数组中的所有元素。虽然它让我意识到一个可能的'解决方案'就是洗牌,然后按照我需要的数量迭代数组,但我想知道如何做到这一点呢?

2 个答案:

答案 0 :(得分:1)

这是一种已知的算法。你需要的是Knuth-Fisher-Yates shuffle的变种http://en.wikipedia.org/wiki/Knuth_shuffle

将所有数字添加到集合中。如果所有数字都是连续的,那么只需使用for-loop

填充该集合
Repeat this until there's only one number in the collection:
    generate a random number using the length of the collection.
    remove the number from the collection.  

At this point there's only one element in the collection. So remove the only number from the collection.

答案 1 :(得分:1)

我在写OP的过程中没有立刻意识到这一点,但我想到的方法实际上满足了所有的先决条件:

首先确保

import java.util.Collections;

迭代你的数组,调用shuffle方法然后简单地调用索引,这是一个使用4个图标的例子:

ImageIcon[] stack_ex = new ImageIcon[11];
for (int i = 1; i < 12; i++)     
     stack_ex[i - 1] = new ImageIcon("C:/Image_directory/" + i + ".jpg");
}

随机播放阵列:

Collections.shuffle(Arrays.asList(stack_ex));


JButton alpha = new JButton(stack_ex[0]);
JButton beta = new JButton(stack_ex[1]);
JButton gamma = new JButton(stack_ex[2]);
JButton delta = new JButton(stack_ex[3]);

四个图标位置始终是随机的离散的。