This article mainly introduces the information about random sorting of arrays in the JavaScript study notes. For more information, see
Recommended reading:Array Summation Method for JavaScript learning notes
Add, delete, modify, and query the array of JavaScript learning notes
The sort () and reverse () methods are provided in JavaScript to re-sort array items. However, these two methods often cannot meet our actual business needs, such as random shuffling in poker games.
In this article, we will learn how to complete the effects of the above example and some knowledge about random sorting of arrays.
After checking information about random sorting of arrays on the Internet, we can see Math. random. Open the browser controller and enter:
Math. random ()
Math. random () returns 0 ~ A random number between 1. As we all know, sort () can call a function as a parameter. If the value returned by this function is-1, it indicates that item a in the array is placed before item B. In this way, you can write a random function to make Math. the random number of random () is compared with 0.5. 5.-1 is returned (a is in front of B), and 1 is returned (B is in front of ):
function randomSort(a, b) {return Math.random() > 0.5 ? -1 : 1;}
Example:
var arr = [1,2,3,4,5,6,7,8,9];arr.sort(randomSort);
In this way, we can implement the example at the beginning of the article:
Although the previous method achieves random sorting of arrays, it always feels that the positions of each element sent to the new array are not random. As in the preceding example, the original first key value of an element with a value of 1 in array arr is 0. After random sorting, the probability of a key value of 1 being 0-8 is the same. Then, the value is decreased because the sort () method is compared sequentially.
To solve this problem, we can use the following recursive method:
Function randomSort (arr, newArr) {// If the length value of the original array arr is equal to 1, the original array has only one value, its key value is 0 // push this value to the new array newArr if (arr. length = 1) {newArr. push (arr [0]); return newArr; // equivalent to recursive exit} // obtain a random number var random = Math based on the original array length. ceil (Math. random () * arr. length)-1; // pushes a random value from the original array to newArr in the new array. push (arr [random]); // Delete the arr of the original array. splice (random, 1); return randomSort (arr, newArr );}
In this way, we can use:
for (var i = 0; i < 10; i++) {var arr=[1,2,3,4,5,6,7,8,9];var newArr=[];randomSort(arr,newArr);console.log(newArr);}
Output result:
After the randomSort (arr, newArr) function is executed, the original array arr is cleared.
If you use this method to start shuffling, You need to reset the pukePic array in the resetPic () function:
In addition to the above two methods, @ Traveller shared an article "Implementation of random sorting algorithms for array elements" in DIV. IO. This article provides three methods for random sorting of array items:
Use the array sort method to randomly sort array elements
Array.prototype.shuffle = function(n) {var len = this.length ,num = n ? Math.min(n,len) : len,arr = this.slice(0);arr.sort(function(a,b){return Math.random()-0.5;});return arr.slice(0,num-1);}
Randomly swap elements in the array
Lib = {} lib. range = function (min, max) {return min + Math. floor (Math. random () * (max-min + 1);} Array. prototype. shuffle = function (n) {var len = this. length, num = n? Math. min (n, len): len, arr = this. slice (0), temp, index; for (var I = 0; I
Randomly extract an element from the original array and add it to the new array.
Lib = {} lib. range = function (min, max) {return min + Math. floor (Math. random () * (max-min + 1);} Array. prototype. shuffle = function (n) {var len = this. length, num = n? Math. min (n, len): len, arr = this. slice (0), result = [], index; for (var I = 0; I
Shuffling Algorithm
The basic principle of random array sorting is the shuffle algorithm (Fisher-Yates shuffle ):
It is an algorithm used to disrupt the order of finite sets.
Principle
Defines an array (shuffled). The length is the length of the original array (arr ).
Take the random value rand from 0 to index (initial 0), shuffled [index] = shuffled [rand], shuffled [rand] = arr [index]
Index ++; repeat Step 2 until index = length-1
Is the shuffled value assignment process from 0 to length-1, and the new value is arr [index], the value of shuffled [index] is the random value of shuffled [rand] in the assigned element, because there will be two duplicate values, so shuffled [rand] is equal to the newly added arr [index].
Shuffle method in underscore. js
function random(min, max) {if (max == null) {max = min;min = 0;}return min + Math.floor(Math.random() * (max - min + 1));};function shuffle(arr) {var length = arr.length,shuffled = Array(length);for (var index = 0, rand; index < length; index++) {rand = random(0, index);if (rand !== index) shuffled[index] = shuffled[rand];shuffled[rand] = arr[index];}return shuffled;}
Practical application:
var arr = [1,2,3,4,5,6,7,8,9];for (var i = 0; i < 10; i++){console.log(shuffle(arr));}
The result of Chrome output is as follows:
Similarly, the shuffling algorithm is used to complete the example at the beginning of the article:
There are also simpler and easier-to-understand methods:
function shuffle(arr) {var i, j,temp;for (i = arr.length - 1; i > 0; i--) {j = Math.floor(Math.random() * (i + 1));temp = arr[i];arr[i] = arr[j];arr[j] = temp;}return arr;};
Summary
This article summarizes and collects information about random sorting of arrays. Of course there are still many ways to implement similar functions in the workshop. Here we just collect and sort out these methods. If you have better methods, please share them with us in the comments.
The above content is a brief introduction to the random sorting of arrays in the JavaScript study notes. I hope it will help you!