randomize (shuffle) an array

Given an integer n, write a function to return an array of size n, containing each of the numbers from 0 to n-1 in a random order. The numbers should not repeat and each number must be in array only once.

Example:

if n = 3, one possible array returned would be [2, 0, 1].

[2, 0, 0] is not a valid array since '0' is duplicated and the '1' does not appear.

The de-facto unbiased shuffle algorithm is the Fisher-Yates (aka Knuth) shuffle.


var arr_len = 10; // length of input array



function random_array( num ) {

    var i, j, tmp,

        raw_array = [];



    for ( i = 0; i < num; i++ ) { // create array

        raw_array.push(i);

    }



    for ( i = num - 1; i > 0; i-- ) { // swap elements in array randomly using Fisher-Yates (aka Knuth) Shuffle

        j = Math.floor( Math.random() * (i + 1) );

        tmp = raw_array[i];

        raw_array[i] = raw_array[j];

        raw_array[j] = tmp;

    }

    //alert( 'n = ' + num + '; array = [ ' + raw_array + ' ]' ); // alert for demonstation

    document.getElementById('log').innerHTML = 'n = ' + num + '; array = [ ' + raw_array + ' ]';

    // return raw_array;

}



random_array( arr_len );

Leave a Comment