我需要知道是否有一种方法可以为一个字符串分配一个数字范围,并让一个随机数发生器选择一个数字,并根据它给该字符串返回的数字。我知道那令人困惑所以继承人就是一个例子,
item1 = 0 to 15
item2 = 16 to 35
item3 = 36 to 65
item4 = 66 to 85
item5 = 86 to 95
item6 = 96 to 99
现在说随机数发生器生成数字63,所以作为回报你会得到item3
由于
答案 0 :(得分:2)
您可以使用NavigableMap
。这允许您为项目指定权重,并使用ceilingEntry方法根据权重随机选择项目。
Random rand = new Random();
...
int rnd = rand.nextInt(totalWeight + 1);
String elem = map.ceilingEntry(rnd).getValue();
要生成地图,只需执行以下操作即可。每个项目都会添加到地图中,并包含其总重量以及之前的所有项目。在您的情况下,您不必将已运行总计加起来,因为您已经有了范围。
NavigableMap<Integer, String> map = new TreeMap<Integer, String>();
String[] items = new String[]{"item1","item2","item3","item4","item5","item6"};
int[] weights = new int[]{15,35,65,85,95,99};
int totalWeight = 0; // track this for use in random number generation
for (int i = 0; i < weights.length; i++) {
totalWeight = weights[i];
map.put(totalWeight, items[i]);
}
答案 1 :(得分:0)
如果概率,项目数量和项目本身没有变化,这是一种简单的方法:
public String getRandomString() {
int number = (int)(Math.random() * 100)
if(number >= 0 && number <= 15) return "item1";
if(number >= 16 && number <= 35) return "item2";
if(number >= 36 && number <= 65) return "item3";
if(number >= 66 && number <= 85) return "item4";
if(number >= 86 && number <= 95) return "item5";
if(number >= 96 && number <= 99) return "item6";
// the computer will never get to here, but the compiler doesn't know that
// (though it might happen if you change the numbers above, and don't
// cover all the numbers 1 to 99)
throw new RuntimeException("this shouldn't happen!");
}