html - JavaScript: Pick percentage numbers -


so i'm having issue relates picking winner based on percentage.

now method pick random decimal between 1 - 0. example: [.55 or .33] , when generate number, percentage picked based on random decimal picked as.

example of this:

numbers calculated: user 1 chance> 25%. user 2 chance> 75%.

so i'm trying figure out how pick user based on decimal created.

i have javascript code here of it, don't know rest , i'm willing take possible.

<!doctype html> <html> <head> <script> function nowget(){     var picked = math.random() * (1 - 0) + 0;     var numb1 = .25;     var numb2 = .75;      if(numb1 >= picked && picked <= numb1){         alert("25% chance wins win %: " + picked);     }else if(numb2 >= picked && picked <= numb2){         alert("75% chance wins win %: " + picked);     }else{         alert("nothing picked. win %: " + picked);     } }  </script> </head>  <body>  <h1>my web page</h1>  <p id="demo">a paragraph</p>  <button type="button" onclick="nowget()">try it</button>  </body> </html> 

what trying achieve getting closest number out of array of numbers. here's great answer question: https://stackoverflow.com/a/8584940/612847

adapted specific scenario, here's solution:

function closest (num, arr) {     var curr = arr[0];     var diff = math.abs (num - curr);     (var val = 0; val < arr.length; val++) {         var newdiff = math.abs (num - arr[val]);         if (newdiff < diff) {             diff = newdiff;             curr = arr[val];         }     }     return curr; }  var array = [.25, .75]; var number = math.random(); var winner = closest(number, array); console.log(winner); 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -