import java.util.Arrays;
import java.util.Random;
public class Selection {
public static void main(String[] args) {
//input arrays
String[] categories = {"iPad 2","iPod Touch 5","iPod Touch 4","iPhone 3G/3GS","iPad 1","iPad Mini","iPhone 4/4S","iPhone 5","iPad 3/4"};
int[] quantities = {2,2,6,94,104,150,174,205,236};
//ensure that there's at least one item for each category
int[] distributions = {1,1,1,1,1,1,1,1,1};
int[] intervals = new int[9];
intervals[0] = 2;
for (int i=1;i<9;i++) {
intervals[i] = intervals[i-1]+quantities[i];
}
Random generator = new Random();
int range = intervals[intervals.length-1];
for (int j=0;j<51;j++) { //to fill the remaining 51 slots according roughly to their proportions
int randomInt = generator.nextInt(range); //generate an integer between 0 and 2+2+6+94+104+150+174+205+236 at random
if (randomInt < intervals[0]) {
distributions[0]++;
}
else if (randomInt >= intervals[0] && randomInt < intervals[1]) {
distributions[1]++;
}
else if (randomInt >= intervals[1] && randomInt < intervals[2]) {
distributions[2]++;
}
else if (randomInt >= intervals[2] && randomInt < intervals[3]) {
distributions[3]++;
}
else if (randomInt >= intervals[3] && randomInt < intervals[4]) {
distributions[4]++;
}
else if (randomInt >= intervals[4] && randomInt < intervals[5]) {
distributions[5]++;
}
else if (randomInt >= intervals[5] && randomInt < intervals[6]) {
distributions[6]++;
}
else if (randomInt >= intervals[6] && randomInt < intervals[7]) {
distributions[7]++;
}
else {
distributions[8]++;
}
}
System.out.println("array(9) {");
for (int k=0; k< 9; k++) {
System.out.println(" [\""+categories[k]+"\"] => int("+distributions[k]+")");
}
System.out.println("}");
}
}
我已经测试了上面完整且有效的代码,并希望代码是不言自明的。
这是我刚刚得到的示例输出:
array(9) {
["iPad 2"] => int(1)
["iPod Touch 5"] => int(1)
["iPod Touch 4"] => int(2)
["iPhone 3G/3GS"] => int(6)
["iPad 1"] => int(7)
["iPad Mini"] => int(11)
["iPhone 4/4S"] => int(8)
["iPhone 5"] => int(13)
["iPad 3/4"] => int(11)
}
这个想法很简单:我们首先为每个类别保留一个项目,这会占用 9 个插槽。一个一个地考虑剩下的 51 个插槽,每个插槽都有机会根据其比例进入各自的类别。由于项目的总数不够大,而且我们使用随机函数生成一个整数,所以我们不能保证结果完全符合每个类别的比例。尽管如此,我认为该解决方案足以满足您的目的。