Javascript Get Random result with probability for specific array

前端 未结 3 960
被撕碎了的回忆
被撕碎了的回忆 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: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($("").attr("src", shirts[pos][0]));
    $(".price").html("$" + shirts[pos][1]);
    
    

提交回复
热议问题