Search code examples
javaarraysindices

java randomize indices in an array


I have looked at Randomize or shuffle an array Randomize or shuffle an array

I am not sure if this is the best approach to make.

I want to randomize the indices of an array with 3 items.

12 4 5

int numbers[] = new int[3];

I tried using the Maths.Random

int randomoption2 = opmin + (int)(Math.random() * ((opmax - opmin) + 1));

but I then have an issue with repetition of the indices values. What is the best approach to randomize the indices so there is no repetition .

eg

a[1] = 2;

I don't want two elements in the array coming back with an indices of one

http://www.exampledepot.com/egs/java.util/coll_Shuffle.html

public class randomorder {

        public static void main(String [] args)
        {
            randomorder();  
            System.out.println(randomorder());
        }

        public static ArrayList randomorder(){
            ArrayList nums = new ArrayList();
            nums.add(1);
            nums.add(2);
            nums.add(3);

            Collections.shuffle(nums);
            return nums;
        }
    }

I now need to store each of the numbers in variables so they can be outputted

System.out.println(options[0]);


Solution

  • Use Collections.shuffle:

    Integer[] numbers = { 1, 2, 3, 4, 5 };
    Collections.shuffle(Arrays.asList(numbers));
    

    See it working online: ideone

    It uses the Fisher-Yates shuffle internally. This is an efficient shuffling algorithm that won't give you duplicates.

    Related