开发者

Randomize numbers within a subset

I have a array of integer numbers (say 1,2,3,4,5 or 1,2,3, ... 10 or 1,2,3, ... 50) from which I would like to get a random set of numbers ordered differently 开发者_开发百科every time. Is there a utility method to do this?

e.g. for 1,2,3,4,5 post randomization it might be either [1,5,4,2,3 or 2,1,3,5,4 or 3,1,2,4,5 or ...]

I would like to know if there is a java utility method / class which already provides this capability?


Collections.shuffle?

That won't help directly with an array, but if you convert it to a List<Integer> it'll work. (You can't use Arrays.asList with an int[], unfortunately.)

Alternatively, you can implement a Fisher-Yates Shuffle yourself very easily - in fact, that Wikipedia page even has an implementation in Java :) (I'd change it to take a Random reference as a parameter, however - you don't want to create a new instance of Random every time you call it.)


see java.util.Collections.shuffle Your array needs to be an colletion. You can use java.util.Arrays.asList for this.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜