The _javascript techniques of array random ordering of JavaScript learning notes

Source: Internet
Author: User
Tags array sort rand random shuffle shuffle

Recommended reading: An array summation method of JavaScript learning notes

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

The sort () and reverse () methods are provided in JavaScript to reorder the array items. But many times these two methods do not meet our actual business needs, such as the random shuffle in poker games.

In this article, learn how to do the above example, and some relevant knowledge about array random ordering.

On the Internet to check about the random ordering of the relevant data, have seen the figure of Math.random (). Open the browser controller and enter:

Math.random ()

It can be seen from the graph that math.random () gets the random number between 0~1. As we all know, sort () can call a function as a parameter if the value returned by this function is 1, which means that item A in the array is ranked before item B. In this way, you can write a random function, let math.random () random out of the number and 0.5 as a comparison, if greater than. 5, return 1 (a row in front of B), conversely return 1 (b row in front of a):

function Randomsort (A, b) {return
math.random () > 0.5? -1:1;
}

Look at an example:

var arr = [1,2,3,4,5,6,7,8,9];
Arr.sort (Randomsort);

This allows you to implement the example effect at the beginning of the article:

Although the preceding method implements the random ordering of arrays, it is always felt that the placement of each element in the new array is not random. As in the previous example, an element with a value of 1 in the array arr, its original key value is 0, and the probability of 1 of the key values required for 0-8 is the same. It is then decremented here because the sort () method is compared sequentially.

In response to this phenomenon, we can use the following recursive method to handle:

function Randomsort (arr, newArr) {
//if the length value of the original array arr equals 1 o'clock, the original array has only one value, its key value is 0
//And the value is pushed to the new array newArr
if ( Arr.length = = 1) {
Newarr.push (arr[0]);
return NEWARR; Equivalent to recursive exit
}
//Take out a random number based on the length of the original array
var random = Math.ceil (Math.random () * arr.length)-1;
Push the random value in the original array into the new array newArr
Newarr.push (Arr[random]);
Corresponds to the deletion of the original array arr the corresponding array item
arr.splice (random,1);
Return Randomsort (arr, NEWARR);
}

In this way, we can use this:

for (var i = 0; i < i++) {
var arr=[1,2,3,4,5,6,7,8,9];
var newarr=[];
Randomsort (Arr,newarr);
Console.log (NEWARR);
}

Output results:

After the Randomsort (Arr,newarr) function is executed, the original array arr is emptied.

If you use this method to do an example of the beginning of an article shuffle, you will reset the Pukepic array in the Resetpic () function:

In addition to the above two methods, @Traveller shared an array element randomization algorithm implementation in Div.io, this article provides an implementation of three kinds of random ordering of array items:

Using the array sort method to randomly sort a group of 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);
}

Elements within an array of randomly exchanged

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<len;i++) {
index = Lib.range (i,len-1);
temp = Arr[i];
Arr[i] = Arr[index];
arr[index]=temp;
}
Return Arr.slice (0,num);
}

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<num;i++) {
index = Lib.range (0,len-1-i);
or Result.concat (Arr.splice (index,1))
Result.push (Arr.splice (index,1) [0]);
}
return result
}

Shuffle algorithm

The basic principle of array random ordering is the shuffle algorithm (Fisher–yates Shuffle):

is an algorithm that disrupts the order of a finite set.

Principle

Defines an array (shuffled), length is the original array (arr) length
Take 0 to index (initial 0) random value rand, Shuffled[index] = Shuffled[rand], Shuffled[rand] = Arr[index]
index++; Repeat the second step until index = length-1
Is the shuffled from 0 to length-1, and the value of the newly added value is Arr[index],shuffled[index] is the random value in the assigned element Shuffled[rand, because there will be two duplicate values, so Shuffled[rand] equals the new added value Arr[index]

The 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 < i++) {Console.log (
Shuffle (arr));
}

The results of the chrome output are as follows:

Similarly, use the shuffle algorithm to complete the first example of an article:

There is also a simpler and easier to understand wording:

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;
};

Summarize

This article mainly summarizes and collects relevant information about random ordering of arrays. There are, of course, many ways to implement similar functions in the people's shops, where they are collected and sorted, and if you have a better way, welcome to share them with us in the comments.

The above content is a small series to introduce the JavaScript learning notes of the array of random ordering of the relevant introduction, I hope to help you!

Related Article

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.