[英]I am generating random numbers from 1~10, but I want to give number 8 high priority, so that 8 number should generate more times, how can I do this?
This means the number 8 have high priority, so it will generate more times then other numbers.这意味着数字 8 具有高优先级,因此它会产生比其他数字更多的次数。 for example:
例如:
In given example you can see that the number 8 has high priority that`s why it generate more times.在给定的示例中,您可以看到数字 8 具有高优先级,这就是它生成更多次数的原因。
private int getRandom(int _minValue, int _maxValue) {
Random random = new Random();
return random.nextInt(_maxValue - _minValue + 1) + _minValue;
}
A quick way to do this if you only need to increase the weight of a single value, is by generating extra values from Random
that you associate with the specific number you want to weigh more.如果您只需要增加单个值的权重,一个快速的方法是从
Random
生成额外的值,您将这些值与您想要增加权重的特定数字相关联。 For example, generate 1 to 20 and consider all numbers above the max of 10 as 8.例如,生成 1 到 20,并将所有大于最大值 10 的数字视为 8。
Here is an example method based on yours, that would take 2 more parameters to determine what number you to weigh more, and how much more you want it to weigh:这是一个基于您的方法的示例方法,它需要另外 2 个参数来确定您要称重多少,以及您希望它称重多少:
private int weightedRandom(int minValue, int maxValue, int weightedNum, int weight) {
Random random = new Random();
int randomVal = random.nextInt(maxValue - minValue + weight + 1) + minValue;
if (randomVal > maxValue) {
randomVal = weightedNum;
}
return randomVal;
}
Tested with below (helper method changed to static
to test from main
):通过以下测试(辅助方法更改为
static
以从main
进行测试):
public static void main(String[] args) {
int max = 10;
int weight = 4;
int weightedNum = 8;
int min = 1;
for (int k = 0; k < 50; k++ ) {
System.out.print(weightedRandom(min, max, weightedNum, weight) + " ");
}
}
Test Run of 50 method calls: 50 个方法调用的测试运行:
8 4 8 5 1 1 5 6 8 3 3 9 10 6 10 8 8 8 9 6 8 8 10 2 8 1 5 4 8 2 8 8 6 10 10 4 9 8 8 1 1 10 9 7 7 8 9 7 5 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.