0

I'm having trouble on generating a random int from an array. In some cases the output is an int, but not an element of this array.

public static int array1[] = new int [] {0,3,6,9,12,15,18,21,24,27,30,33,36};
public static int rand;

public static int random()
{
    int max = array1[12];
    int min = array1[0];
    rand = (int) Math.floor(Math.random()*(max - min)+1);
    return rand;
}

What am I doing wrong?

Jason Baker
  • 2,332
  • 3
  • 20
  • 26
XhensB
  • 770
  • 3
  • 10
  • 28
  • possible duplicate of [Generating random integers in a range with Java](http://stackoverflow.com/questions/363681/generating-random-integers-in-a-range-with-java) – Joe Nov 02 '14 at 02:42
  • 1
    @Joe This is not a duplicate. – Tom Nov 02 '14 at 02:43
  • The task here is to pick a random index, and the linked question covers that comprehensively. – Joe Nov 02 '14 at 02:46
  • 2
    @Joe Oh, right, a single "low vote" answer covers that. I missed it, because it was "hidden" by the other answers, which do not match this question. Sorry. – Tom Nov 02 '14 at 02:57

3 Answers3

3

Your current algorithm is calculating a random number between the first and last element in the array.

You should, instead, retrieve a random element from the array. To accomplish this, it would be better to generate a random number between 0 and the length of your array (exclusive), then return the element at that index.

Luiggi Mendoza
  • 81,685
  • 14
  • 140
  • 306
0

Rather than generating a random element from the range defined by the largest and smallest element of your array, generate a random element in the range [0..12].

In other words, pick a random index in your array

Jason Baker
  • 2,332
  • 3
  • 20
  • 26
0

You'd be better off creating a random int between 0 and the exclusive upper bound of the array. Then you can just use your random number as an array index, and your random value will always be one of the provided values.

As it stands, you're not really using the array - all you've done is use the first and last indices to establish the inclusive lower and exclusive upper bounds of your random int, and the result will be any int therebetween.

furkle
  • 4,844
  • 1
  • 12
  • 22