Algorithm for obtaining random numbers with the same probability

Source: Internet
Author: User

In the past few days, when I started a lottery program at the annual meeting of the company, I thought the algorithm was very simple. I put the employee data into the list and used the list label as the random number to be obtained, based on the random number, the winner is determined. Later tests showed that the random number distribution was very uneven. It was later known that the random numbers obtained by the computer were all pseudo-random numbers. When the lottery was very fast, the random numbers obtained were very uneven. Therefore, a delay was required for each lottery. Later, the algorithm was re-designed and finally implemented. The algorithm principle is similar to the binary search process. A coin has the same positive probability and negative probability. When the number of samples increases infinitely, the probability of sampling is 50%. The Code is as follows: copy the code public partial class MainWindow: Window {string s; int number; public MainWindow () {InitializeComponent ();} public int getRandom () {// string [] arr = new string [5] {"", "yes", "1", "", "team "}; random r = new Random (); int num = 2; int choose = r. next (num); return choose; // MessageBox. show (arr [choose]. toString ();} public string GRandom (int n) {// if () if (n = 0) {// s = getRandom () + s; // System. threading. thread. sleep (1); return s;} if (n % 2 = 0) {n = n/2;} else {n = (n-1)/2; // s = getRandom () + s;} s = getRandom () + s; System. threading. thread. sleep (20); GRandom (n); // System. threading. thread. sleep (1); return s;} public Int32 Estimate (int n) {string num = GRandom (n); number = Convert. toInt32 (num, 2); if (number> n-1) {// num = ""; s = ""; Estimate (n );} // else return number;} private void Button_Click (object sender, RoutedEventArgs e) {for (int I = 0; I <100; I ++) {label1.Content + = Estimate (200) + ";"; s = "";}}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.