2014-12-04 64 views
0

我如何可以随机的ArrayList 让老指数必须不一样的新的索引所有元素ArrayList的随机

例如 与3项

后的列表ArrayList的随机

旧索引< - >新指标

1<-->2 <--different 
2<-->1 <--different 
3<-->3 <--same is not allowed 

我想牛逼o确保它会是

1<-->3 <--different 
2<-->1 <--different 
3<-->2 <--different 
+0

您确定要随机?我认为有约束排除了随机性。或者干脆重新排列?如果是这样,你可以简单地重新分配给'(index + n)%array.length',其中n是任意数字。 – Sach 2014-12-04 06:56:46

+0

有趣的是,一些OP在他们花了10分钟发布问题后大约30秒看似消失...;) – 2014-12-04 07:17:01

+0

http://stackoverflow.com/questions/4228975/how-to-randomize-arraylist http:// stackoverflow .com/questions/9701639/is-collections-shuffle-really-random-enough-practical-examples-seem-to-deny -t – Ian2thedv 2014-12-04 07:19:51

回答

0
Collections.shuffle(List<?> list) 

这应该与列表工作不包含空值:

static <T> void shuffleList(List<T> list) { 
    List<T> temp = new ArrayList<T>(list); 
    Random rand = new Random(); 

    for (int i = 0; i < list.size(); i++) { 
     int newPos = rand.nextInt(list.size()); 
     while (newPos == i||temp.get(newPos)==null) { 
      newPos = rand.nextInt(list.size()); 
     } 
     list.set(i, temp.get(newPos)); 
     temp.set(newPos,null); 
    } 
} 

对于列表空值:

static <T> void shuffleList(List<T> list) { 
    List<T> temp = new ArrayList<T>(list); 
    Integer [] indexes=new Integer[list.size()]; 
    for (int i=0;i<list.size();i++){ 
     indexes[i]=i; 
    } 
    Random rand = new Random(); 

    for (int i = 0; i < list.size(); i++) { 
     int newPos = rand.nextInt(list.size()); 
     while (newPos == i||indexes[newPos]==null) { 
      newPos = rand.nextInt(list.size()); 
     } 
     list.set(i, temp.get(newPos)); 
     indexes[newPos]=null; 
    } 
} 
+2

我不认为这是正确的,因为它不能保证每个元素都在新的位置上结束。 – 2014-12-04 07:05:49

+0

不,我错了。它是正确的。你的解释虽然有点稀疏。 – 2014-12-04 07:07:00

+0

根据这个问题,这是不正确的。 OP希望所有元素位于不同的位置。这并不能保证这一点。 – Ian2thedv 2014-12-04 07:09:14

2

这是你必须实现自己。

  • 洗牌可能是一系列随机掉期(例如,交换1→4, 交换3→2)。
  • 跟踪每个元素的新位置(例如,包含5个元素和上述洗牌操作的列表,4 3 2 1 5)。
  • 如果任何元素仍旧在旧位置(在该示例中为5),则 继续洗牌。

听起来很有趣。