0

Suppose there is an array :

int arr[] = {0,1,2}

Is there a way I can generate a random number out of 0,1,2 (i.e from the array) ?

3
  • you mean pick randomy one of these numbers witch the array is holding ? Commented Apr 4, 2013 at 12:07
  • @A4L yeah I mean the same Commented Apr 4, 2013 at 12:10
  • QuadroQ explains how, Sano shows how. Commented Apr 4, 2013 at 12:12

4 Answers 4

6

try this

    import java.util.Random;

    Random random = new Random();
    System.out.println(arr[random.nextInt(arr.length)]);
Sign up to request clarification or add additional context in comments.

Comments

2

Sure. You should generate a number between 0 and arr.length-1, round it to a int number and then take the arr[your_random_number] element.

int random_index = (int) round(Math.random() * (arr.length - 1));

then your element would be arr[random_index]

4 Comments

what do you mean by repeated?
This is random, but not fair, as the rounding causes 0 and arr.length - 1 to both occur roughly half as often as any other number. Better to use aRandom.nextInt(arr.length) or (int) (Math.random() * arr.length)
yeah, might be ... i'm not really that familiar with the statistical problems random might have.
The standard way to do this is (int) (Math.random()*arr.length) - this gives us exactly what we want with equal probability.
1

If you want unique element each time from the array then try this:

Integer arr[] = {0,1,2}
Collections.shuffle(Arrays.asList(arr));
for(int unique: ar)
   System.out.println(unique);

Shuffle method of Collections will randomly shuffle the given array .

7 Comments

this won't work as you expect for a int[], only for a Integer[]. With arr being int[] this Arrays.asList(arr) will return a list of length 1, which makes no sense shuffling...
@jlordo Using Random can generate same number more than once...yes?
this is not what the questioner wants, this will alter the list placing each element randomly somewhere else.
@A4L: No, it is no placing each element somewhere else, it does nothing, because arr is a int[]. I'll post some code in a minute.
Look at this http://ideone.com/kCK0TE for int[] and this http://ideone.com/u8tjnZ for Integer[]. and see the difference.
|
0

This will pick a number randomly out of the array.

public static void main(String[] args) 
{
    int arr[] = {0,1,2};
    System.out.println(arr[(int)(Math.random()*arr.length)]);
}

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.