# 一道面试题引发的有关随机数的思考(8)

RandSSN：

public class RandSSN : Rand
{
private int _baseNum;//表示是以几为基础
public int BaseNum
{
get
{
return _baseNum;
}
}
private Random _rand;
private RandSSN(int baseNum, int maxNum)
{
_rand = new Random();

UpdateMaxNum(baseNum, maxNum);
}
private NumAnalyse na;
public void UpdateMaxNum(int baseNum, int maxNum)
{
_baseNum = baseNum;
_maxNum = maxNum;
na = new NumAnalyse(_baseNum, maxNum);
}
public static RandSSN GetInstance(int baseNum, int maxNum)
{
if (rand == null || !(rand is RandSSN))
{
rand = new RandSSN(baseNum, maxNum);
}
else if (rand is RandSSN && rand.MaxNum != maxNum || ((RandSSN)rand).BaseNum != baseNum)
{
((RandSSN)rand).UpdateMaxNum(baseNum, maxNum);
}
return (RandSSN)rand;
}
private int SubNext()
{
return _rand.Next(1, _baseNum + 1);
}
override public int Next()
{
int result = 0;
NumAnalyse tempNa = new NumAnalyse(_baseNum);
int num = SubNext() - 1;
bool preEqual = true;
for (int i = 0; i < na.NumList.Count; i++)
{
if (num > na.NumList[i] && preEqual)
{
result = Next();
break;
}
else
{
if (preEqual)
{
preEqual = (num == na.NumList[i]);
}
num = SubNext() - 1;
}
}
return result != 0 ? result : tempNa.GetReaNum;
}
}

static void TestRandSSN()
{
RandSSN rand = RandSSN.GetInstance(10, 101);
TestRand(rand);
}

耗时: 38.6652701893819 秒
Average:0.0099010;Max:0.0099880;Min:0.0098261
Max:0.0099880, Max-Average:0.0000870, Bits:0.8788000%
Min:0.0098261, Min-Average:-0.0000749, Bits:-0.7563900%

• 本文已收录于以下专栏：

举报原因： 您举报文章：一道面试题引发的有关随机数的思考(8) 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)