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

上一篇文章(http://blog.csdn.net/xzjxylophone/article/details/6853802)中末尾我们提出可以换成其他的随机数来计算。

看以下的类:

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
			{
				tempNa.NumList.Add(num);
				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%

在此关于随机数的一系列的遐想就到此结束了

你可能感兴趣的:(面试,测试,null,Random,Class)