I have an array
(1,2,2,2,3,3,4,5,5,5,5,5,5)
I must find randomly one position taking into account the sum of elements. for example if the 5 - is six times and the 1 - is only one, so the 5 must six times be often in random
I have an array
(1,2,2,2,3,3,4,5,5,5,5,5,5)
I must find randomly one position taking into account the sum of elements. for example if the 5 - is six times and the 1 - is only one, so the 5 must six times be often in random
You need to get a random index of the array:
int randomIndex = Random.nextInt(array.length);
int randomValue = array[randomIndex]
Something like this?
int array[] = {1,2,2,2,3,3,4,5,5,5,5,5,5};
int randomIndex = Random.nextInt(array.length);
int randomNumber = array[randomIndex];
Like another answer said, you need an int in the range 0 : length-1.
I would advise using:
Random r = new Random();
int index = r.nextInt(array.length);
int randomValue = array[index];
Here you can see the differences between Math.random() and the nextInt() method of a Random Object:
try this:
1 import java.util.Random;
2
3 class Rnd {public static void main(String... args) {
4 int[] data = new int[]{1,2,2,2,3,3,4,5,5,5,5,5,5};
5 System.out.print(data[new Random().nextInt(data.length)]);
6 }
7 }
nextInt()
method "Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive), drawn from this random number generator's sequence.". Because random is uniformly distributed, you'll get your number as more often, as more often it includes in an array.