JAVA - How do I generate a random number that is w

2019-09-27 14:45发布

问题:

This question already has an answer here:

  • Random weighted selection in Java 7 answers

How do I generate a random number in Java, (using Eclipse) that is weighted towards certain numbers?

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%.

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.

回答1:

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() 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

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 random