随機函數是産生随機數的函數。即以等機率産生某一範圍(認為規定)内的任意數。例如,産生1~10範圍内的整數,随機函數每次都以10%的機率産生1,2,3,……,10中的任何一個數。
機率随機數:是在1-10内産生随機數,但是每個數生成的機率不同。例如1-9機率為10%,10的機率是%90;
一,問題模拟:
比如:求1-5的數指定機率下的随機,機率如下:
數字 | 機率 |
---|---|
1 | 10% |
2 | |
3 | |
4 | 20% |
5 | 50% |
二,方法設想:
1, 将每個數按照機率占比放到一個數組中(比如:[1,2,3,4,4,5,5,5,5] ),然後求【0~數組長度】的随機數,所求值再取其數組值,即為所求;
2, 将指定機率作為權值添加到一個數組
- 将指定機率作為權值添加到一個數組:arr;
- 求數組arr中的所有數值的和:total ;
- 求 [0-total]中間的随機數:r;
- 找這個随機數r的在數組arr哪個arr[i] 中,然後傳回這個:i。
- 使用這個i解決問題(比如上述問題:i+1即為所求)
三,代碼實作:
class Program
{
static void Main(string[] args)
{
// 機率數組
int[] arr = new int[] { 10, 10, 10, 20, 50 };
Console.WriteLine("機率随機數~");
Console.WriteLine("随機到的索引:"+ ProbabilityRandomRumber(arr));
}
/// <summary>
/// 機率随機數
/// </summary>
/// <param name="rate"></param>
/// <returns></returns>
public static int ProbabilityRandomRumber(int[] rate)
{
int total = 0;
for (int i = 0; i < rate.Length; i++)
{
total += rate[i];
}
Random myRandom = new Random();
int r = myRandom.Next(0, total);
Console.WriteLine("随機數是:" + r);
int t = 0;
for (int i = 0; i < rate.Length; i++)
{
t += rate[i];
if (r < t)
return i;
}
return 0;
}
}
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIyZuBnL4czN3ATO0YTMwETMwEjMwIzLc52YucWbp5GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.png)