title: Use rand5(), to generate rand7() (with the same probability)
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/137783/expand-a-random-range-from-15-to-17">Expand a random range from 1–5 to 1–7</a>  </p>
  </blockquote>
  
  
  
  <p>I have seen the question in here: <a href="http://www.mytechinterviews.com/equal-probability-between-1-and-7" rel="nofollow noreferrer">Link</a></p>
  
  <p>The solution the author provided didn't seem to generate the same probability.</p>
  
  <p>For example, the number 4, out of 10k calls for the function, was returned 1-2 times (when the other numbers, like 2, were returned about 2k times each).</p>
  
  <p>Maybe I understood wrong, or I wrote the algorithm wrong, but here:</p>
  
  <pre><code>    static int rand5()
      {
          return new Random().Next(1, 6);
      }
      static int rand7()
      {
          while (true)
          {
              int num = 5 * (rand5() - 1) + rand5();
              if (num &lt; 22) return ((num % 7) + 1);
          }
      }
      static void Main(string[] args)
      {
          int limit = 10000;
          int[] scores = new int[7];
          for (int i = 0; i &lt; limit; i++)
          {
              scores[rand7() - 1]++;
          }
          foreach (int n in scores)
          {
              Console.Write(n + " ");
          }
          Console.WriteLine();
      }
  </code></pre>
  
  <p>Thanks in advance.</p>