java - Math.random 重复自身

标签 java math random

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

相关文章:

python为数组创建卷积函数

matlab - MATLAB 中的布丰针

c# - System.Random 的深度克隆

给定半径为1.00的圆坐标的java数学计算

matlab - 矩阵和数组有什么区别?

Java- Math.random() : Selecting an element of a 13 by 13 triangular array

java - 构建项目错误

java - 过时的 com.ms.security 的等效安全功能是什么?

Java 流操作调用

java - 自动启动 GUI Java jar Lubuntu