我正在寻找一种方法,我可以随机生成一个字符的统计(如技能,攻击,防御,.)。让我们来说说我的数据
1-100
现在我想要的是
1- 30 a概率为30% 31 - 50 a概率为45% 51 - 75 a 20%的概率 76-100 a概率为5%
我知道我可能会使用Random
类或Math.random()
,但不确定如何使用。
提前感谢!
发布于 2016-02-11 01:16:14
一种选择是在0到100之间生成一个随机数,然后使用一系列if-else
语句来确定要为您的字符生成哪些统计数据:
public void printRandomStats() {
Random random = new Random();
int next = random.nextInt(101);
if (next <= 30) {
// this will happen 30% of the time
System.out.println("Generating stats from 1-30");
} else if (next <= 75) {
// this will happen 45% of the time
System.out.println("Generating stats from 31-75");
} else if (next <= 95) {
// this will happen 20% of the time
System.out.println("Generating stats from 76-95");
} else {
// this will happen 5% of the time
System.out.println("Generating stats from 96-100");
}
return;
}
发布于 2016-02-11 02:12:00
解决问题的最佳方法是创建一个非一致的概率值列表。然后从这个列表中随机选择一个值。例如:
如果我们有如下清单:
{5 , 5 , 5 , 5 , 10 , 10 , 10 , 20, 20 ,30}
我们的可能性会是这样的;
5 => 40% --- 10 => 30% --- 20 => 20% --- 30 => 10%
您可以使用以下简单的方法实现该解决方案:
private static int generateStat()
{
ArrayList<Integer> stats = new ArrayList<Integer>();
//first parameter is probability and second is the value
stats.addAll(Collections.nCopies(30, (int)(Math.random()*30)));
stats.addAll(Collections.nCopies(45, (int)(Math.random()*20)+30));
stats.addAll(Collections.nCopies(20, (int)(Math.random()*25)+50));
stats.addAll(Collections.nCopies(5, (int)(Math.random()*25)+75));
return stats.get((int)(Math.random()*100));
}
https://stackoverflow.com/questions/35334911
复制相似问题