在類庫橫行的今天,請支持DIY ,直接看代碼(有注釋)
view plaincopy to clipboardPRint?
using System;
namespace MyRandom
{
public class Rand
{
private long seed; //隨機數種子
//用系統時間作為隨機種子
public Rand()
{
string str = DateTime.Now.Day.ToString();
str += DateTime.Now.Hour.ToString();
str += DateTime.Now.Minute.ToString();
str += DateTime.Now.Second.ToString();
str += DateTime.Now.Millisecond.ToString();
this.seed = long.Parse(str);
}
//用戶自定義隨機種子
public Rand(long Value)
{
this.seed = Value;
}
//產生非負偽隨機數
public long Next()
{
long l = this.seed;
l = l * l;
string strTime = l.ToString();
int w = strTime.Length / 3;
string str = "";
for (int i = w; i < strTime.Length - w; i++)
str += strTime[i];
l = long.Parse(str);
return l;
}
//產生上限為Value的偽隨機數
public long Next(long Value)
{
if (Value < 0)
return -1;
long l = this.seed;
l = l * l;
string strTime = l.ToString();
int w = strTime.Length / 3;
string str = "";
for (int i = w; i < strTime.Length - w; i++)
str += strTime[i];
l = long.Parse(str);
return l % Value;
}
//產生下限為minValue上限為maxValue的偽隨機數
public long Next(long minValue, long maxValue)
{
if (minValue < 0 || maxValue < 0 || minValue > maxValue)
return -1;
long l = this.seed;
l = l * l;
string strTime = l.ToString();
int w = strTime.Length / 3;
string str = "";
for (int i = w; i < strTime.Length - w; i++)
str += strTime[i];
l = long.Parse(str);
return l % (maxValue - minValue) + minValue;
}
//偽隨機數填充指定的比特數組
public void NextBytes(byte[] buffer)
{
long Value = 0;
Value = this.Next() % 255;
for (int i = 0; i < buffer.Length; i++)
{
Value = Value * Value;
string strTime = Value.ToString();
int w = strTime.Length / 3;
string str = "";
for (int j = w; j < strTime.Length - w; j++)
str += strTime[j];
Value = long.Parse(str);
Value = Value % 255;
buffer[i] = (byte)Value;
}
}
//產生0.0到1.0的偽隨機數
public double NextDouble()
{
long l = this.Next(0, 100000);
if (l == 100000)
return 1.0;
l = l * l;
string strTime = l.ToString();
int w = strTime.Length / 3;
string str = "0.";
for (int i = w; i < strTime.Length - w; i++)
str += strTime[i];
double d = double.Parse(str);
return d;
}
}
}
http://blog.csdn.net/gisfarmer/archive/2009/02/03/3860282.aspx
新聞熱點
疑難解答