Design of red envelope algorithm

Source: Internet
Author: User

JS version (source http://q.cnblogs.com/q/70893/)

var m = [], Money  = +,  num = 2,  min = max =  15;//Each person first gets the minimum amount to the hand for (var i = 0; i < i++) {  M.P Ush (2);} Money = money-(num * min), while (Money > 0) {  //between 0-14 random  var idx = Math.floor (Math.random () * max);//This represents 0-14  if (M[idx] < max) {    M[idx] + = 1;    Money-= 1;  }} Console.log (m);
The algorithm avoids negative situation, and embodies good programming habits, the algorithm complexity is not high, and the mine-clearing algorithm is similar to random mines, the same is to let index random
For example

function Initmine (width,height,m)

{var basic=[];//original array

var sum=width*height;//total number of squares

for (var x=0;x<sum; x + +)

{

Basic[x]=x;

}

for (Var i=0;i<m;i++)

{

var Rn=math.floor (Math.random () * (basic.length));

Minepostarray.push (Basic[rn]);

Basic.splice (rn,1);// avoid random numbers to produce duplicates

Console.log (Minepostarray[i]);

}

}

Red Envelope algorithm design (turn)

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.