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)
6
solved JAVA – How do I generate a random number that is weighted towards certain numbers? [duplicate]