【发布时间】:2016-02-19 06:40:57
【问题描述】:
到目前为止,我的代码几乎可以正常工作。说明在方法之上。我遇到的唯一问题是Math.random(); 在多次调用时会重复。我想知道是否有防止Math.random(); 重复的解决方案;
/**
* Apply an "efficient selection shuffle" to the argument.
* The selection shuffle algorithm conceptually maintains two sequences
* of cards: the selected cards (initially empty) and the not-yet-selected
* cards (initially the entire deck). It repeatedly does the following until
* all cards have been selected: randomly remove a card from those not yet
* selected and add it to the selected cards.
* An efficient version of this algorithm makes use of arrays to avoid
* searching for an as-yet-unselected card.
* @param values is an array of integers simulating cards to be shuffled.
*/
public static void selectionShuffle(int[] values) {
ArrayList<Integer> temp=new ArrayList<Integer>();
int size=52;
for(int j=0;j<size;j++){
/*int random=(int)(Math.random()*51);
temp.add(random);
values[j]=temp.get(j);*/
int random=(int)(Math.random()*51);
temp.add(values[random]);
values[j]=temp.get(j);
}
}
【问题讨论】:
-
Math.random()将运行 52 次,因为您已将其置于循环中。每次调用该方法时它都会运行。这是你的问题吗? -
或者你的意思是
Math.random()返回的值? -
我建议你尝试在你的方法上面实现注释。您当前的代码没有这样做。 (我还建议使用
Random类而不是Math.random。) -
您可以在循环外使用 create
Random random = new Random();,然后在循环内调用random.nextDouble()。 -
@PragnaniKinnera,因为
values是一个原始数组,所以这不起作用。如果你有番石榴,你可以Collections.shuffle(Ints.asList(values))。