July 2, 2010

Random sort of array elements

Recently I came across problem of sorting randomly elements of some array. Here's what I came up with :
Pseudocode :

for each element in the array
calculate a random number with index range from 0 to array size -1
store the current element in a temporary variable
replace the current element in the array with the element at the random index
replace the element at random index with the element at temporary variable

Solution :
        int[] buttons = new int[16];

        for(int i=0; i<16; i++){
            buttons[i] = i;
        }

        int rand;
        int temp;
        Random random;

        random = new Random(System.currentTimeMillis());
        for (int i = 0; i < buttons.length; i++) {
            rand = (random.nextInt() & 0x7FFFFFFF) % buttons.length;
            temp = buttons[i];
            buttons[i] = buttons[rand];
            buttons[rand] = temp;
        }

No comments:

Post a Comment

stat4u