title: Choose between multiple options with defined probability
body: <p>I have a scenario where I need to show a different page to a user for the same url based on a probability distribution,</p>
  
  <p>so for e.g. for 3 pages the distribution might be</p>
  
  <pre><code>page 1 - 30% of all users
  page 2 - 50% of all users
  page 3 - 20% of all users
  </code></pre>
  
  <p><strong>When deciding what page to load for a given user, what technique can I use to ensure that the overall distribution matches the above?</strong></p>
  
  <p>I am thinking I need a way to choose an object at "random" from a set X { x1, x2....xn } except that instead of all objects being equally likely the probability of an object being selected is defined beforehand. </p>
  
  <hr>
  
  <p>Thanks for the input everyone, after doing some prototyping, this is what I ended up using</p>
  
  <pre><code>private static int RandomIndexWithPercentage(Random random, int[] percentages) {
      if (random == null) {
          throw new ArgumentNullException("random");
      }
  
      if (percentages == null || percentages.Length == 0) {
          throw new ArgumentException("percentages cannot be null or empty", "percentages");
      }
  
      if(percentages.Sum() != 100) {
          throw new ArgumentException("percentages should sum upto 100");
      }
  
      if (percentages.Any(n =&gt; n &lt; 0)) {
          throw new ArgumentException("percentages should be non-negative");
      }
  
      var randomNumber = random.Next(100);
      var sum = 0;
      for (int i = 0; i &lt; percentages.Length; ++i) {
          sum += percentages[i];
          if (sum &gt; randomNumber) {
              return i;
          }
      }
  
      //This should not be reached, because randomNumber &lt; 100 and sum will hit 100 eventually
      throw new Exception("Unexpected");
  } 
  </code></pre>