c#获取相同概率随机数的算法代码
这几天在做公司年会的一个抽奖软件,开始做的的时候,认为算法是很简单的,把员工的数据放进list里,把list的标号作为需要获取的随机数,根据得到的随机数就确定是谁中奖。后来测试发现,随机数的分布是非常不均匀的。后来才知道,原来计算机获取的随机数都是伪随机数,当抽奖的速度非常快的时候,获取的随机数是非常不均匀的,所以在每次抽奖的时候要添加延时。后来重新设计算法,最终实现了。
算法原理跟二分查找的过程有点像。一枚硬币抽中正、反面的概率是一样,当抽样的次数无限增多,抽中的概率是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 = "";
}
}
}
以上算法不是非常好,取消延时,将random对象设置为全局变量。修改版代码如下:
string s;
int number;
random r = new random();
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;
grandom(n);
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 < 1000; i++)
{
label1.content = estimate(200);
s = "";
}
//以下为测试
//int a = 0, b = 0, c = 0, d = 0, f = 0;
//for (int i = 0; i < 1000; i++)
//{
// //label1.content = estimate(2);
// int content = estimate(5);
// s = "";
// switch (content)
// {
// case 0:
// a ++;
// break;
// case 1:
// b ++;
// break;
// case 2:
// c ++;
// break;
// case 3:
// d ++;
// break;
// case 4:
// f ++;
// break;
// }
// label1.content = a;
// label2.content = b;
// label3.content = c;
// label4.content = d;
// label5.content = f;
//}
}
}
}