本文整理汇总了C#中Random类的典型用法代码示例。如果您正苦于以下问题:C# Random类的具体用法?C# Random怎么用?C# Random使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Random类属于命名空间,在下文中一共展示了Random类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
n = Convert.ToInt32(Session["n"]);//Convert.ToInt32(n_txt.Text);
dx = Convert.ToInt32(Session["dx"]);//Convert.ToInt32(n_txt.Text);
dy = Convert.ToInt32(Session["dy"]);//Convert.ToInt32(n_txt.Text);
npow = Convert.ToInt32(Math.Pow(2, n));
boxes = new int[npow, npow,2];
//if (!IsPostBack)
{
if (Session["create"].ToString() != "1")
{
Random rnd = new Random();
for (int i = 0; i <= boxes.GetUpperBound(0); i++)
{
for (int k = 0; k <= boxes.GetUpperBound(1); k++)
{
boxes[i, k, 0] = rnd.Next(1, 6);
}
}
}
else
{
CreateBoxes(true, 0, 0, boxes.GetUpperBound(0), boxes.GetUpperBound(1),dx,dy);
}
fillBoxPanel();
}
}
示例2: GenerateRandomCode
// Function to generate random string with Random class.
private string GenerateRandomCode()
{
Random r = new Random();
string s = "";
for (int j = 0; j < 5;j++)
{
int i = r.Next(3);
int ch;
switch (i)
{
case 1:
ch = r.Next(0, 9);
s = s + ch.ToString();
break;
case 2:
ch = r.Next(65, 90);
s = s + Convert.ToChar(ch).ToString();
break;
case 3:
ch = r.Next(97, 122);
s = s + Convert.ToChar(ch).ToString();
break;
default:
ch = r.Next(97, 122);
s = s + Convert.ToChar(ch).ToString();
break;
}
r.NextDouble();
r.Next(100, 1999);
}
return s;
}
示例3: AutoGeneratedPassword
public static string AutoGeneratedPassword(string sEMail)
{
string sRondomPassword;
sRondomPassword = string.Empty;
Random oRandom = new Random();
// 6 Characters Password...
for (int iRunner = 0; iRunner < 6; iRunner++)
{
int iRandom = oRandom.Next(0, 61);
sRondomPassword = sRondomPassword + PassChars.Substring(iRandom, 1);
}
// Get PassKey from Session
string sPassKey = PassKey;
// Get Encrypted Password...
//string sCryptedPassword = CreatePasswordHash(sPassword);
object ErrorMessage;
UserInfo oUser = new UserInfo();
bool UserCreated = oUser.ResetSiteUserPassword(sEMail, sRondomPassword, out ErrorMessage);
oUser = null;
// Function Returning New Password
return sRondomPassword;
}
示例4: PosTest1
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Verify Double value equals with Equals(Double).");
try
{
Double d1 = new Random(-55).NextDouble();
Double d2 = d1;
if (!d1.Equals(d2))
{
TestLibrary.TestFramework.LogError("001.1", "Method Double.Equals(Double) Err.");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("001.2", "Unexpected exception: " + e);
TestLibrary.TestFramework.LogInformation(e.StackTrace);
retVal = false;
}
return retVal;
}
示例5: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
OpenFlashChart.OpenFlashChart chart = new OpenFlashChart.OpenFlashChart();
chart.Title=new Title("AreaHollow");
AreaHollow area = new AreaHollow();
Random random=new Random();
area.Colour = "#0fe";
area.DotSize = 2;
area.FillAlpha = 0.4;
area.Text = "Test";
area.Width = 2;
area.FontSize = 10;
IList values = new List<double>();
for (int i = 0; i < 12; i++)
values.Add(random.Next(i, i*2));
area.Values = values;
chart.AddElement(area);
XAxis xaxis=new XAxis();
// xaxis.Labels = new AxisLabel("text","#ef0",10,"vertical");
xaxis.Steps = 1;
xaxis.SetRange(0,12);
chart.X_Axis = xaxis;
YAxis yaxis = new YAxis();
yaxis.Steps = 4;
yaxis.SetRange(0,20);
chart.Y_Axis = yaxis;
string s = chart.ToString();
Response.Clear();
Response.CacheControl = "no-cache";
Response.Write(s);
Response.End();
}
示例6: GenerateSMP
/// <summary>
/// 生成手机密码:通过用户编号
/// </summary>
/// <param name="sUserNo">用户编号</param>
/// <returns>已生成手机密码的用户的手机号</returns>
public string GenerateSMP(string sUserNo)
{
Random r1 = new Random();
int iRandomPassword;
string sRandomPassword,SM_content,mobile_telephone,sOperCode;
DataSet ds=new DataSet();
//生成密码
iRandomPassword = r1.Next(1000000);
sRandomPassword = fu.PasswordEncode(iRandomPassword.ToString());
ds = fu.GetOneUserByUserIndex(sUserNo);
sOperCode = ds.Tables[0].Rows[0]["User_code"].ToString();
mobile_telephone = ds.Tables[0].Rows[0]["mobile_telephone"].ToString();
sSql = "UPDATE Frame_user SET SM_PWD='" + sRandomPassword + "',SMP_last_change_time=getdate()" +
" WHERE User_code = '" + sOperCode + "'";
sv.ExecuteSql(sSql);
//发送密码
string SMP_validity_period = ds.Tables[0].Rows[0]["SMP_validity_period"].ToString();
SM_content = "欢迎您使用EBM系统!您新的手机密码是:" + iRandomPassword.ToString() + "有效时间为:" + SMP_validity_period + "小时。";
SendSMContentByPhoneCode(mobile_telephone, SM_content);
return mobile_telephone;
}
示例7: SetRandomEdge
public static void SetRandomEdge(int[,] graph, int n)
{
bool found = false;
int i = 0;
int j = 0;
int count = 0;
Random random = new Random();
for (int k = 0; k < n; k++)
{
for (int l = 0; l < n; l++)
{
if (graph[k, l] != int.MaxValue)
continue;
count++;
if (random.Next(0, count) == 0)
{
found = true;
i = k;
j = l;
}
}
}
if (found)
graph[i, j] = random.Next(1, 10);
}
示例8: Main
// You are given an array of strings. Write a method
// that sorts the array by the length of its elements
// (the number of characters composing them).
static void Main()
{
//variables
string[] array = new string[7];
Random rand = new Random();
//fill the Array with Random strings
for (int i = 0; i < array.Length; i++)
{
string member = null;
for (int k = 0; k < rand.Next(1, 7); k++) //length of strings
{
member = member + RandomString();
}
array[i] = member;
}
#region print original array
Console.Write("{");
Console.Write(String.Join(", ", array));
Console.WriteLine("} -> ");
#endregion
//sort the array by the length of its elements
var SortedArray = array.OrderBy(x => x.Length); //using Linq
#region print sorted array
Console.Write("{");
Console.Write(String.Join(", ", SortedArray));
Console.WriteLine("} ");
#endregion
}
示例9: GuessGame
// guessGame receives user input and returns output
// based on their guess.
private static void GuessGame(object obj)
{
var client = (TcpClient)obj;
NetworkStream stream = client.GetStream();
StreamReader streamR = new StreamReader(stream);
StreamWriter streamW = new StreamWriter(stream);
streamW.AutoFlush = true;
string input;
int guess = 0;
int guesses = 0;
int num = new Random().Next(1, 101);
try {
streamW.WriteLine("+ Hello. I'm thinking of a number between 1 and 100. Can you guess it?");
while(guess != num) {
input = streamR.ReadLine();
guesses++;
if (!int.TryParse(input, out guess) || (guess < 1 || guess > 100)) {
guesses--;
streamW.WriteLine("! Invalid input, please enter only numbers between 1 and 100.");
} else if (guess < num) {
streamW.WriteLine("> Higher.");
} else if (guess > num) {
streamW.WriteLine("< My number is lower.");
}
}
streamW.WriteLine("* That's it. Good job. It took you {0} guesses. Thanks for playing.", guesses);
stream.Close();
} catch (Exception) {
stream.Close();
return;
}
}
示例10: CreateImage
/// <summary>
/// ����ͼƬ
/// </summary>
/// <param name="checkCode">�����</param>
private void CreateImage(string checkCode)
{
int iwidth = (int)(checkCode.Length * 11.5);//����������趨ͼƬ���
Bitmap image = new Bitmap(iwidth, 20);//����һ������
Graphics g = Graphics.FromImage(image);//�ڻ����϶����ͼ��ʵ��
Font f = new Font("Arial",10,FontStyle.Bold);//���壬��С����ʽ
Brush b = new SolidBrush(Color.Black);//������ɫ
//g.FillRectangle(new System.Drawing.SolidBrush(Color.Blue),0,0,image.Width, image.Height);
g.Clear(Color.White);//������ɫ
g.DrawString(checkCode, f, b, 3, 3);
Pen blackPen = new Pen(Color.Black, 0);
Random rand = new Random();
/*�����
for (int i = 0; i < 5; i++)
{
int y = rand.Next(image.Height);
g.DrawLine(blackPen, 0, y, image.Width, y);
}
*/
System.IO.MemoryStream ms = new System.IO.MemoryStream();
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
Response.ClearContent();
Response.ContentType = "image/Jpeg";
Response.BinaryWrite(ms.ToArray());
g.Dispose();
image.Dispose();
}
示例11: MultipleAnnounce
public void MultipleAnnounce()
{
var announceCount = 0;
var random = new Random();
var handle = new ManualResetEvent(false);
for (var i = 0; i < 20; i++)
{
var infoHash = new InfoHash(new byte[20]);
random.NextBytes(infoHash.Hash);
var tier = new TrackerTier(new[] {_uri.ToString()});
tier.Trackers[0].AnnounceComplete += (sender, args) =>
{
if (++announceCount == 20)
handle.Set();
};
var id = new TrackerConnectionID(tier.Trackers[0], false, TorrentEvent.Started,
new ManualResetEvent(false));
var parameters = new OctoTorrent.Client.Tracker.AnnounceParameters(0, 0, 0, TorrentEvent.Started,
infoHash, false, new string('1', 20),
string.Empty, 1411);
tier.Trackers[0].Announce(parameters, id);
}
Assert.IsTrue(handle.WaitOne(5000, true), "Some of the responses weren't received");
}
示例12: RandomStringArray
static string[] RandomStringArray()
{
Random rand = new Random();
int len = rand.Next(3, 10); // [3;10)
string[] stringArr = new string[len];
// let's build the words observing the frequency of the letters in English
// so for example the vowels will appear more often
// http://www.oxforddictionaries.com/words/what-is-the-frequency-of-the-letters-of-the-alphabet-in-english
double[] frequencies = { 0.002, 0.004, 0.007, 0.010, 0.020, 0.031, 0.044, 0.061, 0.079, 0.100, 0.125, 0.155, 0.185, 0.217, 0.251, 0.287, 0.332, 0.387, 0.444, 0.511, 0.581, 0.652, 0.728, 0.803, 0.888, 1.000, };
char[] letters = { 'q', 'j', 'z', 'x', 'v', 'k', 'w', 'y', 'f', 'b', 'g', 'h', 'm', 'p', 'd', 'u', 'c', 'l', 's', 'n', 't', 'o', 'i', 'r', 'a', 'e', };
for (int i = 0; i < len; i++)
{
int wordLen = rand.Next(1, 10); // determines the length of the current string
string word = string.Empty;
for (int j = 0; j < wordLen; j++)
{
double frequency = rand.Next(2, 1000) / 1000d; // [0.002;0.999]
int index = Array.BinarySearch(frequencies, frequency);
if (index < 0) index = ~index;
char letter = letters[index];
word += letter;
}
stringArr[i] = word;
}
return stringArr;
}
示例13: BtnAdd_Click
protected void BtnAdd_Click(object sender, EventArgs e)
{
SqlConnection vid = new SqlConnection("Data Source=(local);Initial Catalog=Ring;Integrated Security=True");
{
Random rnd = new Random();
SqlCommand orders = new SqlCommand("INSERT INTO dbo.orders (email,order_ID,month,year,jewel_ID,price,credit_Card) VALUES (@email,@order_ID,@month,@year,@jewel_ID,@price,@credit_Card)", vid);
orders.Parameters.AddWithValue("@email", Session["username"]);
int holder = rnd.Next(10000000,99999999);
orders.Parameters.AddWithValue("@price", ddlPrice.Text);
orders.Parameters.AddWithValue("@jewel_ID", ddlJewel.Text);
holder = rnd.Next(10000000, 99999999);
orders.Parameters.AddWithValue("@order_ID", holder.ToString());
orders.Parameters.AddWithValue("@month", DateTime.Now.Month.ToString());
orders.Parameters.AddWithValue("@year", DateTime.Now.Year.ToString());
holder = rnd.Next(10000000, 99999999);
orders.Parameters.AddWithValue("@credit_Card", holder.ToString());
holder = rnd.Next(10000000, 99999999);
SqlCommand inventory = new SqlCommand("UDATE dbo.Inventory SET jewel_ID='"+holder+"'WHERE jewel_ID='"+ ddlJewel.Text+"'", vid);
vid.Open();
orders.ExecuteNonQuery();
inventory.ExecuteNonQuery();
vid.Close();
if (IsPostBack)
{
Server.Transfer("Account.aspx", true);
}
}
}
示例14: CreateJToken
private static JToken CreateJToken(Random rndGen, int depth)
{
if (rndGen.Next() < CreatorSettings.NullValueProbability)
{
return null;
}
if (depth < MaxDepth)
{
switch (rndGen.Next(10))
{
case 0:
case 1:
case 2:
// 30% chance to create an array
return CreateJArray(rndGen, depth);
case 3:
case 4:
case 5:
// 30% chance to create an object
return CreateJObject(rndGen, depth);
default:
// 40% chance to create a primitive
break;
}
}
return CreateJsonPrimitive(rndGen);
}
示例15: Run
public override async Task Run()
{
int itemId, amount;
if (HasQuestStarted(2051))
{
itemId = 4031032;
amount = 1;
}
else
{
int[] rewards = new[] {
4020007, 2,
4020008, 2,
4010006, 2,
1032013, 1
};
var rand = new Random();
int index = rand.Next(rewards.Length / 2);
itemId = rewards[index];
amount = rewards[index + 1];
}
if (GainItem(itemId, amount))
{
SetField(101000000);
}
else
{
//TODO: Make more GMS-like.
Talker.Notify("Please check whether your ETC. inventory is full.");
}
}