-1

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

Bali C
  • 30,582
  • 35
  • 123
  • 152

4 Answers4

3

You need to get a random index of the array:

int randomIndex = Random.nextInt(array.length);
int randomValue = array[randomIndex]
Jakub Zaverka
  • 8,816
  • 3
  • 32
  • 48
3

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];
maksimov
  • 5,792
  • 1
  • 30
  • 38
1

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:

Math.random() versus Random.nextInt(int)

Community
  • 1
  • 1
pcalcao
  • 15,789
  • 1
  • 44
  • 64
  • What, no seed? This arrangement might be dangerous if you create a new Random each time. More context is needed. – duffymo Apr 25 '12 at 11:00
  • duffymo: Unless you need to reproduce the results you're usually much better off not giving an explicit seed. This doesn't have anything to do with creating `Random` instances in a loop, though, which, I agree, shouldn't be done (although you can do it in Java if you can live with linearly correlated seeds). – Joey Apr 25 '12 at 11:06
0

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.

dhblah
  • 9,751
  • 12
  • 56
  • 92