开发者

shuffle array elements

I found this code online for shuffling array elements, it works well, but I can't understand the for loop here

shuffle = function(o)
{ 
for(var j, x, i = o.length; i; 
    j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};

any help is appreciate开发者_Go百科d, thank you !


This is basically a misuse of the flexibility of the for loop.

The general syntax for a for loop is:

for (<init>; <condition>; <increment>) {
  <body>
}

which roughly can be expressed as following while loop:

<init>;
while(<condition>) {
   <body>
   <increment>
}

Since both <body> and <increment> are both executed as if they were in the body of the while, anything that can go into the body of a for loop, can also be put in the <increment> expression of the for loop. You just have to separate the statements with commas instead of semicolons.

Thus your for loop is probably better expressed as following while loop:

var j, x, i = o.length; 
while (i) { // same as while(i != 0)
   j = parseInt(Math.random() * i);
   x = o[--i];
   o[i] = o[j];
   o[j] = x;
}


j = parseInt(Math.random() * i); // Getting a random number between 0 to n-1, where n is the length of the array.
x = o[--i]; // Getting the last element of the array and storing it in a variable.
o[i] = o[j]; // Storing the randomly selected index value at the last position.
o[j] = x; // Storing the last element's value in random position.

i value will decrement in each loop iteration and it will replace the last then next to last then so on... and finallly first element of the array with a random element within the aray.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜