function shuffle(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;
};
Not quite sure what the last part is doing
This looks like someone taking up the challenge of "I can do this in one line" , which is a very neat and fun challenge, but has no place in real world code - your coworkers will hate you. So let's expand it into something readable:
function shuffle(o) {
// iterate over the entire input array "o"
for(var i = o.length - 1; i; i--) {
// get the "current" item and save it in variable "x"
var x = o[i];
// generate a random number within the bounds of the array
var j = parseInt(Math.random() * (i + 1));
// The next two lines essentially swap item[i] and item[j]
// set the "current" item to a randomly picked item
o[i] = o[j];
// put the "current" item in the random position
o[j] = x;
}
return o;
};
function shuffle(inputArray) { let i = inputArray.length; while (i) { const j = parseInt(Math.random() * i); // generate random integer smaller than i (Math.random() generates random number between 0 and 1) i = i-1; // swap elements on position i and j const element = inputArray[i]; inputArray[i] = inputArray[j] inputArray[j] = x; } return inputArray; };
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.