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) ?
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) ?
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]
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)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 .
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...arr is a int[]. I'll post some code in a minute.int[] and this http://ideone.com/u8tjnZ for Integer[]. and see the difference.