Showing posts with label collections. Show all posts
Showing posts with label collections. Show all posts

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;
        }

May 25, 2010

Tip of the Day #1 - in or not ?

I really love those small python's built in functions and operators. How to check if variable is in some collection ?

>>> z = x in s
>>> z
True
z will return True if x is in s. Isn't that cool or what ?
stat4u