JAVA - 如何生成对某些数字加权的随机数? [英] JAVA - How do I generate a random number that is weighted towards certain numbers?
问题描述
如何在 Java 中(使用 Eclipse)生成一个随机数,该数对某些数字进行加权?
How do I generate a random number in Java, (using Eclipse) that is weighted towards certain numbers?
例如,我有 100 个数字,每个数字都有 1% 的几率被平均选择.但是,如果某个数字,比如说 5,在 100 中显示了 8 次,那么它现在有 8% 的机会被随机选择,而其他数字仍然是 1%.
Example, I have 100 numbers, each can be equally chosen 1% of the time. However, if a certain number, lets say 5, is displayed 8 times in that 100, it now has an 8% chance to be randomly selected, while the other numbers are still at 1%.
如何编写一个随机生成器,给我 10 个数字并给数字 5 显示 8% 的优势?
How can I write a random generator that gives me 10 numbers and gives the number 5 that 8% advantage to show up?
如果我没有很好地解释,谢谢和抱歉.
Thanks and sorry if I did not explain that well.
推荐答案
public static void main(String[] args){
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(5);list.add(2);// to be continued ...
int randomInt = list.get((int) (Math.random() * list.size()));
System.out.println(randomInt);
}
你会得到你的值列表,然后你只需要随机选择一个索引并取回值
You'll get your List of values, and then you just need to pick randomly an index and get back the value
Math.random()
将在 [0;1[ 中选择一个值,如果乘以 10 个元素的 List
的大小,您将得到一个[0;10[ 中的值,当您将其转换为 int
时,您将获得 10 种可能的索引来查看 List
Math.random()
will pick a value in [0;1[, if you multiply by the size of a List
of 10 elements, you'll a value in [0;10[ , when you cast as an int
you'll get 10 possibilities of index to look into the List
ArrayList
(List
的实现)允许重复元素,所以:如果您添加 1,2,2,3,4,5,6,7,8,9(顺序无关紧要),您将有 10 个元素,每个元素都可以找到 1/10 = 10/100 = 10% 的概率(又名机会),但是出现两次的元素 2 将有 20% 机会在方法中被选中,出现的数字越多,它就越有机会被选中被选择增加,正如你所说的(数字出现的次数)/(元素的总数)(这是基础数学)
The ArrayList
(implementation of List
) allows duplicate element so :
if you add 1,2,2,3,4,5,6,7,8,9 (the order does not matter) you'll have 10 elements with each one to be find with 1/10 = 10/100 = 10% of probability (aka chance), but the element 2 which appears twice will have 20% chance to be choosen in the method, more the number appears more it's chance to be choosen increase, with as you said (number of time the number appears)/(total number of element) (this is basic maths)
这篇关于JAVA - 如何生成对某些数字加权的随机数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!