我有一个数字列表,我需要从该列表中提取一个随机数,但是我需要确保在从所述列表中提取一定数量的数字之后,它们将形成一个预定义的百分位数对于输出数字中的每一组。
编码形式的例子:
int[] nums = {2,3,6};
int twoPer = 25;
int threePer = 45;
int sixPer = 30;
所以在这个例子中,如果我随机抽出100个数字,我需要25个2个,45个3个和30个6个。
答案 0 :(得分:1)
你可能会使用加权随机生成(偏见)之类的东西:
int[] nums = {2,3,6};
int[] numweights = {25, 45, 30}; //weight of each element above
int totalweight = 100;
public int SetRandom() {
int[] weighednums = new int[totalweight]; //new array to hold "weighted" nums
int currentfruit = 0;
int place = 0;
while (currentfruit < nums.length) { //step through each num[] element
for (int i=0; i < numweights[currentfruit]; i++){
weighednums[place] = nums[currentfruit];
place++;
}
currentfruit++;
}
int randomnumber = (int) Math.floor(Math.random() * totalweight);
System.out.println(weighednums[randomnumber] + " at " + randomnumber);
return weighednums[randomnumber];
}
答案 1 :(得分:0)
完成Java的修订:
int[] nums = {2,3,6};
int[] numweights = {25, 45, 30}; //weight of each element above
int totalweight = 100;
public int SetRandom() {
int[] weighednums = new int[totalweight]; //new array to hold "weighted" nums
int currentfruit = 0;
int place = 0;
while (currentfruit < nums.length) { //step through each num[] element
for (int i=0; i < numweights[currentfruit]; i++){
weighednums[place] = nums[currentfruit];
place++;
}
currentfruit++;
}
int randomnumber = (int) Math.floor(Math.random() * totalweight);
System.out.println(weighednums[randomnumber] + " at " + randomnumber);
return weighednums[randomnumber];
}