![](/img/trans.png)
[英]How can I make the script that counts which number occurred most often and counts how many times do each of the 10 random numbers occur
[英]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?
這意味着數字 8 具有高優先級,因此它會產生比其他數字更多的次數。 例如:
在給定的示例中,您可以看到數字 8 具有高優先級,這就是它生成更多次數的原因。
private int getRandom(int _minValue, int _maxValue) {
Random random = new Random();
return random.nextInt(_maxValue - _minValue + 1) + _minValue;
}
如果您只需要增加單個值的權重,一個快速的方法是從Random
生成額外的值,您將這些值與您想要增加權重的特定數字相關聯。 例如,生成 1 到 20,並將所有大於最大值 10 的數字視為 8。
這是一個基於您的方法的示例方法,它需要另外 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;
}
通過以下測試(輔助方法更改為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) + " ");
}
}
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.