An array random ordering _javascript technique of JS random shuffle algorithm

Source: Internet
Author: User
Tags array length random shuffle shuffle first row

Recommended reading: Add, delete, change and check the array of JavaScript learning notes

An array summation method of JavaScript learning notes

A random sort of array of JavaScript learning notes

The shuffle algorithm is a more figurative term that essentially allows an array of elements to be randomly arranged. For example, we have an array in the following figure, with an array length of 9, and the values of the elements within the array sequentially 1~9:

Starting with the array above, all we have to do is disrupt the order of the elements in the array:


Code implementation

Wikipedia's Fisher–yates shuffle entry on the shuffle algorithm is described in detail, the following demo algorithm is based on the theory of the written:

Array.prototype.shuffle = function () {
var input = this;
for (var i = input.length-1 I >=0; i--) {
var randomindex = Math.floor (Math.random () * (i+1)); 
var itematindex = Input[randomindex]; 
Input[randomindex] = Input[i]; 
Input[i] = Itematindex;
}
return input;
}
var temparray = [1, 2, 3, 4, 5, 6, 7, 8, 9, ten]
temparray.shuffle ();
And the result is ...

In the above code, we create a shffle () method that is used to randomly arrange elements within an array. In addition, we mount the method underneath the prototype of the array object, so any array can call the method directly:

var temparray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Working principle

After reading the code, let's see what it does with the array. First, the method selects the last element of the array:

Next, determine the range from which the random element is picked, from the first element of the array to the element selected in the previous step:

Once the range is defined, a random number is selected from it, assuming that the randomly selected element is 4:

Then swap the values of the last element and the randomly selected element:

After the exchange is complete, we have completed the random processing of the last element of the array. Next, select the second-lowest element in the array:

This is done backwards because it makes it easy to determine the range of random selections. This time we assume that the randomly arrived element is 2:


Then the reciprocal first element and the value of the number 2nd element are exchanged to complete the random arrangement of the penultimate element. Then select the penultimate element and repeat the previous action:

The rest is some repetitive work, no more introductions.

Analysis Code

In the previous section to illustrate the shuffle process with a legend, let's look at the shuffle process from the code itself. Let's start with the shuffle function:

Array.prototype.shuffle = function () {
var input = this;
for (var i = input.length-1 I >=0; i--) {
var randomindex = Math.floor (Math.random () * (i+1)); 
var itematindex = Input[randomindex]; 
Input[randomindex] = Input[i]; 
Input[i] = Itematindex;
}
return input;

The shuffle function is mounted under the prototype of the array object, making it easier for the array to call the function directly. Inside the shuffle function, this refers to an array that invokes the shuffle:

var input = this;

In the code above, I refer to this with a new variable, which is the array that calls the shuffle function. Next, look at what's in the For loop:

for (var i = input.length-1 I >=0; i--) {
var randomindex = Math.floor (Math.random () * (i+1)); 
var itematindex = Input[randomindex]; 
Input[randomindex] = Input[i]; 
Input[i] = Itematindex;
}

This loop is used to iterate through all the elements in all arrays and to exchange them randomly. Note that the traversal order is done from the back forward, that is, starting with the element at the input.length-1 position, knowing the first element to traverse into the array. The position in the traversal process is specified by the variable i.

The variable i here is the selected element in the legend above:

Shuffle algorithm

Next, you use two lines of code to pick a random element within a specified range:

var randomindex = Math.floor (Math.random () * (i+1)); 
var itematindex = Input[randomindex];

The variable Randomindex stores a random number that can be used as an index of an array to extract a random element. Note that the maximum value of the random number is not the length of the array, but the value of the variable i.

After the index of the random element is determined, the value of the element is saved with the new variable, and then the value of the selected element and the random element is exchanged:

var itematindex = Input[randomindex];
Input[randomindex] = Input[i]; 
Input[i] = Itematindex;

In these three lines of code, the first row uses the new variable to hold the value of the random element, the second row selects the value of the element Input[i] to the random element Input[randomindex], and the third line assigns the selected element input[i to the value of the random element Itematindex. is essentially a process that swaps the values of two elements, and it's not hard to understand.

At this point, the logic inside the loop is done, and the rest is the repetitive operation.

Random test


The diagram above is a random test chart made using Highcharts to verify the randomness of the shuffle algorithm in this paper in a visual way. The chart will be recalculated and generated each time the page is refreshed.

The data generated from the above figure is computed in this way: first, an array is created (the array used above is [0, 1, 2 ...). 18, 19, 20]), and then use the shuffle algorithm in this article to reorder, and then record the value of each element after sorting. Execute 100,000 times in this step, and finally sum the values at the same index position. After 10,000 executions, the total value of the index should not be the same.

To be calculated by:

The above content is small to introduce the JS random shuffle algorithm to the array of random sort of related narration, hope to help everyone!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.