0

So I'm having an issue that relates to picking a winner based on percentage.

Now for this method I pick a random decimal between 1 - 0. EXAMPLE: [.55 or .33] And when I generate this number, the percentage is picked based on what the random decimal is picked as.

Example of this:

Numbers are calculated: User 1 Chance> 25%. User 2 Chance> 75%.

So I'm trying to figure out how to pick a user based on the decimal created.

I have some JavaScript code here for some of it, I don't know the rest and I'm willing to take ANY help 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 with win %: " + picked);
    }else if(numb2 >= picked && picked <= numb2){
        alert("75% chance wins with win %: " + picked);
    }else{
        alert("Nothing was 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>

1 Answers1

0

What you are trying to achieve is getting the closest number out of an array of numbers. Here's a great answer to your question: https://stackoverflow.com/a/8584940/612847

Adapted to your specific scenario, here's a solution:

function closest (num, arr) {
    var curr = arr[0];
    var diff = Math.abs (num - curr);
    for (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);
Community
  • 1
  • 1
Sergiu
  • 1,397
  • 1
  • 18
  • 33