C# 实现具有 N 个可能范围的“范围”随机数生成器。
using System;
using System.Collections.Generic;
public class MyClass
{
static void Main()
{
var ranges = new List<Range>
{
new Range( 0, 23, 0, 10),
new Range(24, 73, 11, 80),
new Range(74, 100, 81, 100),
};
for (var i = 0; i < 50; i++)
{
var randInt = GetRand(0, 100, ranges);
Console.WriteLine(randInt);
}
Console.ReadKey();
}
static Random _myRandom = new Random();
static int GetRand(int absMin, int absMax, List<Range> ranges)
{
var i = _myRandom.Next(absMin, absMax);
foreach (var range in ranges)
{
if (i >= range.PercentMin && i <= range.PercentMax)
{
return _myRandom.Next(range.ValueMin, range.ValueMax);
}
}
throw new ArgumentOutOfRangeException("Incomplete range?");
}
}
class Range
{
public int PercentMin { get; set; }
public int PercentMax { get; set; }
public int ValueMin { get; set; }
public int ValueMax { get; set; }
public Range(int pctMin, int pctMax, int min, int max)
{
PercentMin = pctMin;
PercentMax = pctMax;
ValueMin = min;
ValueMax = max;
}
}