【发布时间】:2011-11-16 15:54:21
【问题描述】:
我有一个大小为 x 的数组,我需要随机遍历该列表,但每个元素都要访问一次。最有效的方法是什么?
【问题讨论】:
-
but getting to each element once- 这是否意味着您只想获取每个元素一次?并且在改组后不再获得该元素? -
@Rakesh,是的,我只想获取每个元素一次。
我有一个大小为 x 的数组,我需要随机遍历该列表,但每个元素都要访问一次。最有效的方法是什么?
【问题讨论】:
but getting to each element once - 这是否意味着您只想获取每个元素一次?并且在改组后不再获得该元素?
你要找的是随机播放
试试这个-
// Create a list
List list = new ArrayList();
// Add elements to list
// Shuffle the elements in the list
Collections.shuffle(list);
// Create an array
String[] array = new String[]{"a", "b", "c"};
// Shuffle the elements in the array
Collections.shuffle(Arrays.asList(array));
【讨论】:
只需shuffle 数组,然后对其进行迭代。
Collections.shuffle(Arrays.asList(yourArrayReference));
【讨论】:
您可以使用随机数生成器(大多数面向对象语言默认提供该生成器),并使用第二个数组来跟踪您已经检查过的内容。
基本上:
【讨论】:
这是一种节省时间和空间的方法。
import java.util.Enumeration;
import java.util.Random;
public class RandomPermuteIterator implements Enumeration<Long> {
int c = 1013904223, a = 1664525;
long seed, N, m, next;
boolean hasNext = true;
public RandomPermuteIterator(long N) throws Exception {
if (N <= 0 || N > Math.pow(2, 62)) throw new Exception("Unsupported size: " + N);
this.N = N;
m = (long) Math.pow(2, Math.ceil(Math.log(N) / Math.log(2)));
next = seed = new Random().nextInt((int) Math.min(N, Integer.MAX_VALUE));
}
public static void main(String[] args) throws Exception {
RandomPermuteIterator r = new RandomPermuteIterator(100);
while (r.hasMoreElements()) System.out.print(r.nextElement() + " ");
}
@Override
public boolean hasMoreElements() {
return hasNext;
}
@Override
public Long nextElement() {
next = (a * next + c) % m;
while (next >= N) next = (a * next + c) % m;
if (next == seed) hasNext = false;
return next;
}
}
【讨论】: