I have a list of numbers and I need to pull from that list a random number, but I need to make sure that after pulling out a set amount of numbers from said list, that they will form to a pre-defined percentile for each set out of the output numbers.
Example in coded form:
int[] nums = {2,3,6};
int twoPer = 25;
int threePer = 45;
int sixPer = 30;
So in this example if I pulled out 100 numbers at random I would need to have 25 2's, 45 3's and 30 6's.
You might use something like weighted random generation (Biased):
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];
}
Answer complete with revisions for 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];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.