打印随机顺序数组 [英] print an array in random order
问题描述
如何打印在java中以随机顺序数组?
how to print an array in random order in java?
例如:
INT [] myArray的= {5,4,3,2,1};
int[] myArray = {5,4,3,2,1};
打印时,结果应该可能是:
when printed, result should possibly be:
3 2 1 4 5
3 2 1 4 5
或
4 3 2 5 1
4 3 2 5 1
推荐答案
您应该看看写费雪耶茨洗牌。这是pretty容易做到的,高效的。有效地你逻辑阵列变成了洗牌部分和unshuffled一部分分区 - 然后重复从unshuffled部分选择一个随机元素,并与的第一个的从unshuffled部分元素,使将其交换在洗牌部分的那部分。
You should look at writing a Fisher-Yates shuffle. It's pretty easy to do, and efficient. Effectively you logically partition the array into a "shuffled" part and an "unshuffled part" - then repeatedly pick a random element from the unshuffled part and swap it with the first element from the unshuffled part, to make that part of the shuffled part.
另外,创建一个列表与LT;整数GT;
代替,然后使用<一个href=\"http://download.oracle.com/javase/7/docs/api/java/util/Collections.html#shuffle%28java.util.List,%20java.util.Random%29\"><$c$c>Collections.shuffle$c$c>.这是不幸的,没有对数组的相当,但Java的类型系统不作出任何阵列方面做的非常好或的原语通用:(
Alternatively, create a List<Integer>
instead and then use Collections.shuffle
. It's unfortunate that there isn't an equivalent for arrays, but Java's type system doesn't do terribly well in terms of making either arrays or primitives generic :(
(我假设你知道如何做印刷的一面,而且它的洗牌一侧是你的棘手位。)
(I'm assuming you know how to do the printing side, and that it's the shuffling side which is the tricky bit for you.)
这篇关于打印随机顺序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!