我想在(1到6)之间生成随机数,有没有办法改变比其他数字更多的机会?
例如此代码
private void pictureBox5_MouseClick(object sender, MouseEventArgs e)
{
Random u = new Random();
m = u.Next(1,6);
label2.Text = m.ToString();
}
答案 0 :(得分:2)
让p
成为1..5
个数字的概率,而1 - p
概率为6
:
//DONE: do not recreate Random
private static Random s_Generator = new Random();
private void pictureBox5_MouseClick(object sender, MouseEventArgs e) {
const double p = 0.1; // each 1..5 has 0.1 probability, 6 - 0.5
// we have ranges [0..p); [p..2p); [2p..3p); [3p..4p); [4p..5p); [5p..1)
// all numbers 1..5 are equal, but the last one (6)
int value = (int) (s_Generator.NexDouble() / p) + 1;
if (value > 6)
value = 6;
label2.Text = value.ToString();
}
答案 1 :(得分:1)
那不是随机的。如果你想减肥,那么你可以得到6分钟的时间,你可以这样做:
m = u.Next(1,2);
if(m == 2)
{
label2.Text = "6";
}
else
{
label2.Text = u.Next(1,5).ToString();
}
根据你想要的加权你可以改变它 - > 3而不是2获得33.33%的权重,依此类推。否则,正如评论者所说,你必须研究概率分布,以获得更加数学上优雅的解决方案。
答案 2 :(得分:0)
取决于更有可能。一个简单的方法(但不是很灵活)如下:
private void pictureBox5_MouseClick(object sender, MouseEventArgs e)
{
Random u = new Random();
m = u.Next(1,7);
if (m > 6) m = 6;
label2.Text = m.ToString();
}
答案 3 :(得分:0)
如果你想要一个完全随机的1 ... 5分布而且只需要一个6分,那么德米特里似乎是最好的。
如果你要扭曲所有数字,那么试试这个:
答案 4 :(得分:0)
您可以定义获取数组中每个数字的百分比的可能性:
/*static if applicable*/
int[] p = { (int)Math.Ceiling((double)100/6), (int)Math.Floor((double)100/6), (int)Math.Ceiling((double)100/6), (int)Math.Floor((double)100/6), (int)Math.Ceiling((double)100/6), (int)Math.Ceiling((double)100/6) };
////The array of probabilities for 1 through p.Length
Random rnd = new Random();
////The random number generator
int nextPercentIndex = rnd.Next() % 100; //I can't remember if it's length or count for arrays off the top of my head
////Convert the random number into a number between 0 and 100
int TempPercent = 0;
////A temporary container for comparisons between the percents
int returnVal = 0;
////The final value
for(int i = 0; i!= p.Length; i++){
TempPercent += p[i];
////Add the new percent to the temporary percent counter
if(nextPercentIndex <= TempPercent){
returnVal = i + 1;
////And... Here is your value
break;
}
}
希望这有帮助。