Random array sorting and JS shuffling Algorithm Based on js random shuffling Algorithm

Source: Internet
Author: User
Tags shuffle javascript array

Random array sorting and JS shuffling Algorithm Based on js random shuffling Algorithm

Recommended reading:Add, delete, modify, and query the array of JavaScript learning notes

Array Summation Method for JavaScript learning notes

Random sorting of JavaScript learning notes Array

The shuffling algorithm is a term that compares images. In essence, elements in a number group are arranged randomly. For example, we have an array as shown in. The length of the array is 9, and the values of elements in the array are 1 ~ 9:

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


Code Implementation

The Fisher-Yates shuffle entry on Wikipedia provides a detailed description of the shuffle algorithm. The algorithms demonstrated below are also compiled based on the theory:

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, 10 ]tempArray.shuffle();// and the result is...alert(tempArray); 

In the above Code, we created a shffle () method, which is used to randomly arrange the elements in the array. In addition, we mount this method to the prototype of the Array object, so any Array can directly call this method:

var tempArray = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]tempArray.shuffle(); 

Working Principle

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

Next, determine the range for selecting random elements, from the first element of the array to the selected element in the previous step:

After the range is determined, select a random number. Here we assume that the randomly selected element is 4:

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

After the above exchange is complete, it is equivalent to the random processing of the last element of the array. Next, select the penultimate element in the array:

The reason for processing from the back is that it is easy to determine the random range. This time we assume that the random element is 2:


Then, the values of the first and second elements are exchanged to complete the random arrangement of the second and last elements. Then, select the last and third elements and repeat the previous operations:

The rest is repetitive work, so I will not discuss it much.

Analyze code

In the previous section, we used a legend to demonstrate the shuffling process. Next we will look at the shuffling 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, so that the Array can directly call this function. Inside the shuffle function, this references the array that calls the shuffle:

var input = this;

In the code above, I reference this with a new variable, that is, the array that calls the shuffle function. Next, let's take a look at what is done 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 traverses all elements in all arrays and performs random switching. Note that the traversal order is from the back to the front. That is to say, from the element at the input. length-1 position, we know to traverse to the first element in the array. The position in the traversal process is specified by variable I.

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

Shuffling Algorithm

Next, two lines of code are used to select a random element within the specified range:

var randomIndex = Math.floor(Math.random()*(i+1)); var itemAtIndex = input[randomIndex];

The variable randomIndex stores a random number, which can be used as an array index 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 variable I.

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

var itemAtIndex = input[randomIndex];input[randomIndex] = input[i]; input[i] = itemAtIndex;

In the three lines of code, the first line uses the new variable to save the value of the random element; the second line assigns the value of the selected element input [I] to the random element input [randomIndex]; in the third row, the value of the random element itemAtIndex is assigned to the selected element input [I]. Essentially, it is a process of exchanging values of two elements, which is not difficult to understand.

So far, the logic in the loop has been introduced, and the rest are repeated operations.

Random test


It is a random test chart created using Highcharts. it visually verifies the randomness of the shuffling algorithm in this article. This chart is recalculated and generated every time you refresh the page.

The generated data is calculated as follows: first create an array (the array used is [0, 1, 2... 18, 19, 20]), and then use the shuffling algorithm in this article to re-sort, record the value of each element after sorting ...... Perform this step for 100000 times, and finally sum the values at the same index location. The total value of indexes should be slightly different after 10000 queries.

Calculated:

The above content is a description of the JS random shuffling algorithm introduced by xiaobian to the random sorting of arrays. I hope it will help you!

Articles you may be interested in:
  • Php simple shuffling Algorithm
  • In-depth analysis of the shuffles Algorithm in javascript random mode
  • C # shuffling Algorithm
  • C # random sorting of Arrays
  • Php array random sorting Implementation Method
  • How to Implement random array sorting using JavaScript
  • Javascript array random sorting instance analysis
  • Php-based random array merging and sorting (original sorting)
  • Random sorting of JavaScript learning notes Array

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.