yoh*_*ohm 5 java random range dice
我正在进行一些编码练习,但在这个问题上遇到了一些麻烦:
从5个骰子(6面)卷开始,生成[-1-100]范围内的随机数.
我实现了以下方法,但返回的数字不是随机的(称为函数1,000,000次,并且几个数字从未显示在1 - 100中).
public static int generator() {
Random rand = new Random();
int dices = 0;
for(int i = 0; i < 5; i++) {
dices += rand.nextInt(6) + 1;
}
int originalStart = 5;
int originalEnd = 30;
int newStart = 1;
int newEnd = 100;
double scale = (double) (newEnd - newStart) / (originalEnd - originalStart);
return (int) (newStart + ((dices - originalStart) * scale));
}
Run Code Online (Sandbox Code Playgroud)
好吧,所以5个骰子卷,每个有6个选项.如果他们没有订购,你的上限为5-30,如上所述 - 对于1-100来说永远不够.
你需要假设一个订单,这给你一个1,1,1,1,1 - 6,6,6,6,6(基数6)的比例假设1 - > 0值,你有一个5位数的基数生成6个数字.众所周知,6 ^ 5 = 7776独特的可能性.;)
为此,我将给你一个有偏见的随机解决方案.
int total = 0;
int[] diceRolls;
for (int roll : diceRolls) {
total = total*6 + roll - 1;
}
return total % 100 + 1;
Run Code Online (Sandbox Code Playgroud)
感谢JosEdu澄清支架要求
此外,如果你想取消偏向,你可以将范围除以上面描述中给出的maxval,然后乘以你的总数(然后加上偏移量),但你仍然需要确定你使用的舍入规则.
| 归档时间: |
|
| 查看次数: |
2072 次 |
| 最近记录: |