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?

4
  • possible duplicate of Generating random integers in a range with Java Commented Nov 2, 2014 at 2:42
  • 1
    @Joe This is not a duplicate. Commented Nov 2, 2014 at 2:43
  • The task here is to pick a random index, and the linked question covers that comprehensively. Commented Nov 2, 2014 at 2: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. Commented Nov 2, 2014 at 2:57

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.