算法原理跟二分查找的过程有点像。一枚硬币抽中正、反面的概率是一样,当抽样的次数无限增多,抽中的概率是50%。
代码如下:
复制代码
public partial class MainWindow : Window
{
string s;
int number;
public MainWindow()
{
InitializeComponent();
}
public int getRandom()
{
//string[] arr = new string[5] { "我们", "是", "一", "个","团队" };
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 = "";
}
}
}