Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Here's the standard algorithm for this problem

    function weightedRandom(weight, outcomes){
      var total = sum( weight );
      var roll = Math.random()*total; // value in the range [0,total)
      var seen = 0;
      for(let i=0; i<weight.length; i++) {
        seen += weight[i];
        if(roll<seen)
          return outcomes[i];
      }
    }


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: