Issue
This means the number 8 have high priority, so it will generate more times then other numbers. for example :
- first generate no. 4
- second generate no. 8
- third generate no. 2
- fourth generate no. 8
- fifth generate no. 8
In given example you can see that the number 8 has high priority that`s why it generate more times.
private int getRandom(int _minValue, int _maxValue) {
Random random = new Random();
return random.nextInt(_maxValue - _minValue + 1) + _minValue;
}
Solution
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. For example, generate 1 to 20 and consider all numbers above the max of 10 as 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:
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
):
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:
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
Answered By - Nexevis
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.