基于百分比的列表中的随机数

random number from list based off percentage

我有一个数字列表,我需要从该列表中提取一个随机数,但我需要确保在从所述列表中提取一定数量的数字后,它们将形成一个预为输出数字中的每个集合定义百分位数。

编码形式的示例:

int[] nums = {2,3,6};

int twoPer = 25;
int threePer = 45;
int sixPer = 30;

所以在这个例子中,如果我随机抽出 100 个数字,我需要有 25 个 2、45 个 3 和 30 个 6。

您可以使用类似加权随机生成(有偏向)的方法:

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];
}

已完成对 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];
}