2011-09-14 26 views
0

我有一个大小为x的数组,我需要随机浏览列表,但每次都要到达每个元素。什么是最有效的方法来做到这一点?Java:如何随机浏览数组?

+1

的[以从列表中 n个随机元素?]可能重复(http://stackoverflow.com/questions/4702036/take-n-random-elements-from-a-liste) – templatetypedef

+0

'但每个元素获得一次“ - 这是否意味着你只想获取每个元素一次?并且在洗牌后不再获得该元素? – Rakesh

+0

@Rakesh,是的,我只想让每个元素只有一次。 – dee

回答

8

你所寻找的是洗牌

尝试这个 -

// 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)); 
3

只是shuffle的数组,然后遍历它。

Collections.shuffle(Arrays.asList(yourArrayReference)); 
+0

集合未定义。什么是收藏品? – BenRacicot

+1

[Java集合](https://docs.oracle.com/javase/tutorial/collections/)。具体看算法部分。 – Mahesh

0

你可以使用一个随机数发生器,它通常是在大多数面向对象语言默认提供的,并使用第二阵列来跟踪你检查什么了。

本质:

  1. 产生一个随机数
  2. 搜索主阵列的随机数
  3. 如果随机数是不是在已检查的阵列...
  4. ...然后检查元素在主阵列中[随机]
  5. 将随机数添加到已检查阵列的末端
2

这是一个时间和空间高效的方式来做到这一点。

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; 
    } 
} 
+0

这是非常不可读的,虽然可怕的代码。 5分钟后,我仍然没有看到是什么。但是如果它真的遍历一个数组(如OP问),那么数组必须隐藏得很好。这个问题在4年前已经得到解答。 –

+0

它伪随机枚举数组的索引。例如,如果你运行上面的代码,你会得到类似于50 52 3 6 45 40 26 49 92 11 80 2 4 19 86 61 65 44 27 62 5 32 82 9 84 35 38 77 72 7 ...索引0..99。 – aykutfirat

+0

不错,谢谢 – msangel