Comment

Comment by ryani

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];
      }
    }
parent ryani 3 years ago

No comments yet

Be the first to share your thoughts.

Live from the official Hacker News API

A modern reader for Hacker News · SvelteKit + Skeleton