gpt4 book ai didi

java - Math.random 重复自身

转载 作者:行者123 更新时间:2023-11-29 04:50:47 25 4
gpt4 key购买 nike

到目前为止,我的代码几乎可以正常工作。说明在方法之上。我遇到的唯一问题是 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);
}
}

最佳答案

如果您希望整数 0-51 以随机顺序排列且不重复:

  • 按顺序将这些数字添加到列表中
  • 对该列表调用 Collections.shuffle

根据birthday paradox .

关于java - Math.random 重复自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35498883/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com