我如何可以随机的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
我如何可以随机的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
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;
}
}
我不认为这是正确的,因为它不能保证每个元素都在新的位置上结束。 – 2014-12-04 07:05:49
不,我错了。它是正确的。你的解释虽然有点稀疏。 – 2014-12-04 07:07:00
根据这个问题,这是不正确的。 OP希望所有元素位于不同的位置。这并不能保证这一点。 – Ian2thedv 2014-12-04 07:09:14
这是你必须实现自己。
听起来很有趣。
您确定要随机?我认为有约束排除了随机性。或者干脆重新排列?如果是这样,你可以简单地重新分配给'(index + n)%array.length',其中n是任意数字。 – Sach 2014-12-04 06:56:46
有趣的是,一些OP在他们花了10分钟发布问题后大约30秒看似消失...;) – 2014-12-04 07:17:01
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