In-depth analysis of the shuffles Algorithm in javascript random mode _ javascript skills

Source: Internet
Author: User
This article mainly introduces the in-depth analysis of the javascript random shuffling algorithm and provides a complete example. If you need it, you can refer to the shuffling algorithm below, which is a common random problem, games and random sorting are often encountered. It can be abstracted as follows: to obtain a random sequence array of all natural numbers within M.

The first result of the "shuffles algorithm" search on Baidu is "Baidu Library-shuffles algorithm". After scanning the content, many of the content can easily mislead others to go astray, including replacing the array with a linked list, but also a limited optimization (the linked list also introduces the loss of Read efficiency ).

The first method in this article can be simply described as: randomly draw a card and place it in another group; extract again, and draw a blank card again.
"If you leave a blank card, you need to repeat it." This will lead to an increasing chance to leave a blank card, which is obviously unreasonable.
It can be optimized to reduce the number of original cards after the cards are extracted. (Instead of leaving empty cards)
The Code is as follows:

The Code is as follows:


Function shuffle_pick_1 (m) // shuffles // cards
{
// Generate m cards
Var arr = new Array (m );
For (var I = 0; I Arr [I] = I;
}

// Pull a card each time and place it in another pile. It takes a lot of time to extract elements from the array and pull all the elements behind them one by one.
Var arr2 = new Array ();
For (var I = m; I> 0; I --){
Var rnd = Math. floor (Math. random () * I );
Arr2.push (arr [rnd]);
Arr. splice (rnd, 1 );
}
Return arr2;
}

This is also obvious, because if the array is large, deleting an element in the middle will lead to a step forward in the queue, which is a very time-consuming action.
Let's recall, "Why do we delete that element ?" The purpose is to avoid empty cards.
Apart from deleting that element, are there other ways to remove empty cards?
---- Yes. We can place the last undrawn card in the selected position.
Therefore, we can optimize this idea to the following:

The Code is as follows:


Function shuffle_pick (m) // shuffles // cards are selected to optimize cards.
{
// Generate m cards
Var arr = new Array (m );
For (var I = 0; I Arr [I] = I;
}

// Pull a card each time and place it in another pile. Place the last undrawn card on the vacant space.
Var arr2 = new Array ();
For (var I = m; I> 0 ;){
Var rnd = Math. floor (Math. random () * I );
Arr2.push (arr [rnd]);
Arr [rnd] = arr [-- I];
}
Return arr2;
}


In addition to the card draw idea, we can also use the card change idea.
Baidu Library-shuffling algorithm mentioned a card swap idea: "Two random locations are exchanged for a total of n times. The larger n is, the closer it is to random ".
This is wrong. Even if n is very large (for example, 10 cards are exchanged for 10 times), it is very likely that "some cards have not changed their positions ".
Follow this idea and make a small adjustment: change the position of the first card and any card, and complete the round.
The Code is as follows:

The Code is as follows:


Function shuffle_swap (m) // shuffling // card replacement method
{
// Generate m cards
Var arr = new Array (m );
For (var I = 0; I Arr [I] = I;
}

// Replace the first card and any card.
For (var I = 0; I Var rnd = Math. floor (Math. random () * (I + 1 )),
Temp = arr [rnd];
Arr [rnd] = arr [I];
Arr [I] = temp;
}
Return arr;
}

In addition to the idea of card drawing and card changing, we can also use the idea of card inserting: first there is a card, and the second card has two positions that can be randomly inserted (before or after the first card ), the third card has three positions that can be randomly inserted (put behind, inserted in the first place, or inserted in the second place), and so on.
The Code is as follows:

The Code is as follows:


Function shuffle_insert_1 (m) // shuffles // card inserting method
{
// Generate a maximum card each time and place it in front of a random card. It takes a lot of time to insert an element into the array and squeeze all the elements behind it into one place.
Var arr = [0];
For (var I = 1; I Arr. splice (Math. floor (Math. random () * (I + 1), 0, I );
}
Return arr;
}

The above Code also has some problems: as the number of cards increases, card insertion becomes more and more difficult, because card insertion will lead to many cards to be pushed back.
Of course, we can also optimize it as well: first there are n-1 cards, the n cards are placed at the end, and then swap positions with any card.
The Code is as follows:

The Code is as follows:


Function shuffle_insert (m) // shuffles // card placement method optimized version. It can be proved by mathematical induction that the shuffles are even.
{
// Generate a maximum card each time, and replace a random card
Var arr = new Array (m );
Arr [0] = 0;
For (var I = 1; I Var rnd = Math. floor (Math. random () * (I + 1 ));
Arr [I] = arr [rnd];
Arr [rnd] = I;
}
Return arr;
}

All the code is as follows. If you are interested, you can try it on your machine to check whether their respective execution efficiency and final results are theoretically random.

The Code is as follows:





JK: javascript shuffling Algorithm



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.