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)