alex
alex

Reputation: 398

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]);

Upvotes: 0

Views: 1487

Answers (2)

Mark Byers
Mark Byers

Reputation: 838216

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

Upvotes: 6

programmer33
programmer33

Reputation: 652

Just keep three booleans through an array of booleans. Once you hit 0, 1, or 2 index set them to true.

Choose a random position and do while(boolean[number chosen] == true) redo your random choice.

Upvotes: 0

Related Questions