Xhens
Xhens

Reputation: 802

How to generate a random int from an array with given elements?

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?

Upvotes: 0

Views: 63

Answers (3)

furkle
furkle

Reputation: 5059

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.

Upvotes: 0

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

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.

Upvotes: 3

Jason Baker
Jason Baker

Reputation: 2481

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

Upvotes: 0

Related Questions