开发者

How to randomize subset of array in Javascript?

What is the best way to randomize part of the array in Javascript

For example, if I have 100开发者_JAVA百科 items in the array, what is the fast and efficient way of randomizing set of every 10 times. Items between 0 and 9 is randomize within data items[0] to items[9]. Items between 10 to 19 are randomize within data items[10] to items[19] and so on..


You can adjust the array shuffle method that is described here: http://jsfromhell.com/array/shuffle

It is based on Fisher-Yates (Knuth) algorithm (http://en.wikipedia.org/wiki/Fisher–Yates_shuffle).


I would just use the built in slice, concat and sort methods. Something like this.

function shuffle(arr, start, end) {
 return arr.slice(start, end).sort(function() { return .5 - Math.random(); }).concat(arr.slice(end));
};

That's the basic idea, you probably want to make an algorithm to slice every 10 elements, sort and rejoin the sets.

EDIT: Read comments below for why this solution may not be suitable for your needs.


I would split the 1 array into 10 subsets, then perform a shuffle algorithm of your choice on those subsets, and then recombine in the correct order.


The following shuffles the specified chunk of an array in place, as randomly as the environment's random number generator will allow:

function shuffleSubarray(arr, start, length) {
    var i = length, temp, index;
    while (i--) {
        index = start + Math.floor(i * Math.random());
        temp = arr[index];
        arr[index] = arr[start + i];
        arr[start + i] = temp;
    }
    return arr;
}

var a = [1, 2, 3, 4, 5, 6, 7, 8, 9];
alert( shuffleSubarray(a, 2, 5) );
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜