Yesterday, when the annual meeting saw a joke that the only product will be the annual prize draw, the results of the prize is written by the Department of Lottery procedures, the CTO site review code.
Simply think about the implementation of the lottery program, took more than 10 minutes to write a bit, the main use of knowledge has the array to add the deletion, as well as the ES5 array new Indexof,filter method,
In order to refresh the page can still save the winning record, using the Localstorage disk.
Just at the beginning is a random number directly to take the number, found to eliminate the winner is very troublesome, if repeated to recursive call, if the winner is too many to the last random number to the winner of the probability is too large, so swap with two array implementation, a record of the winning number, a record not winning number, The winning one is removed from the other array, and there is no recursive invocation.
The specific implementation is as follows:
var start=1,end=20,luckylist=[],futurelist=[];//luckylist means the winner, Futurelist, who has not been drawn, Start,end says the lottery starts and ends with a number
Initialize an array of all personnel numbers first
for (Var i=start;i<=end;i++) {
Futurelist.push (i);
}
If the page is refreshed, recover from localstoreage
if (Localstorage.getitem ("lucky")) {
Luckylist=localstorage.getitem ("lucky"). Split (",");
Futurelist=futurelist.filter (function (item) {
return Luckylist.indexof (item) ==-1;
})
Console.log (Futurelist)
}
Lottery function, each run once, produces a lucky number
function Raffle () {
var num= math.random () *futurelist.length;
Num=math.floor (num);
var idx=futurelist.indexof (num);
var result= futurelist.splice (idx,1) [0].tostring ();
Luckylist.push (result);
Localstorage.setitem ("lucky", luckylist);
Console.log ("Lottery Result:", result);
}
Clear Localstorge, if you want to reset the program to execute this function
function Clear () {
Localstorage.setitem ("Lucky", "" ");
}
Raffle ();
JavaScript Implementation Lottery Program