Javascript Get Random result with probability for specific array

前端 未结 3 961
被撕碎了的回忆
被撕碎了的回忆 2020-12-20 07:15

i have a array and i need to do it randomly show the output by probability below are my code

var shirts = [
                      [\"images/fantastic-logo.pn         


        
相关标签:
3条回答
  • 2020-12-20 07:26

    For a short array this should be enough, using getRandomInt from Mozilla Developers:

    function getRandomInt(max) {
        return Math.floor(Math.random() * Math.floor(max));
    }
    
    var shirts = [
        ["images/fantastic-logo.png", "12.65"],
        ["images/fantastic-word.png", "10.00"],
        ["images/free-product.png", "15.50"]
    ];
    
    var random = getRandomInt(100);
    var selectedShirt;
    if (random <= 50) {
        selectedShirt = shirts[0];
    } else if (random > 50 && random < 75) {
        selectedShirt = shirts[1];
    } else {
        selectedShirt = shirts[2];
    }
    
    $("#image").html($("<img/>").attr("src", shirts[selectedShirt][0]));
    $(".price").html("$" + shirts[selectedShirt][1]);
    

    Note that you can use less numbers like in Ray's answer. For a bigger array you may use a better approach.

    0 讨论(0)
  • 2020-12-20 07:27

    One option is add a third element which indicate the weight of probability.

    In the example below fantastic-logo.png has 2 to represent 50% and the other 2 only as 1 to represent 25% each.

    Then create a 4 element array [0,0,1,2] - This represent element 0 has 50% chance. element 1 has 25% chance and element 2 has 25% as well.

    Make random from the newly created array and use the value as the position.

    Like:

    var shirts = [
      ["images/fantastic-logo.png", "12.65", 2],
      ["images/fantastic-word.png", "10.00", 1],
      ["images/free-product.png", "15.50", 1]
    ];
    
    //Create a 4 element array based on probability weight
    var probability = shirts.map((v, i) => Array(v[2]).fill(i)).reduce((c, v) => c.concat(v), []);
    
    //Random select from probability array
    var pos = probability[Math.floor((Math.random() * probability.length))];
    
    $("#image").html($("<img/>").attr("src", shirts[pos][0]));
    $(".price").html("$" + shirts[pos][1]);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="image"></div>
    <div class="price"></div>

    0 讨论(0)
  • 2020-12-20 07:27

    function getRandomInt(max) {
      return Math.floor(Math.random() * Math.floor(max));
    }
    /* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random */
    
    getRandomInt(3)

    If you get 0 or 1, the first image is selected. But this method is not elegant. Please refer to the link below.

    Generate A Weighted Random Number

    0 讨论(0)
提交回复
热议问题