本文整理汇总了C#中System.Random类的典型用法代码示例。如果您正苦于以下问题:C# Random类的具体用法?C# Random怎么用?C# Random使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Random类属于System命名空间,在下文中一共展示了Random类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: RandomDatagramTest
public void RandomDatagramTest()
{
Random random = new Random();
for (int i = 0; i != 1000; ++i)
{
Datagram datagram = random.NextDatagram(random.Next(1024));
Assert.AreEqual(datagram, new Datagram(new List<byte>(datagram).ToArray()));
Assert.AreEqual(datagram.GetHashCode(), new Datagram(new List<byte>(datagram).ToArray()).GetHashCode());
Assert.AreNotEqual(datagram, random.NextDatagram(random.Next(10 * 1024)));
Assert.AreNotEqual(datagram.GetHashCode(), random.NextDatagram(random.Next(10 * 1024)).GetHashCode());
if (datagram.Length != 0)
{
Assert.AreNotEqual(datagram, Datagram.Empty);
Assert.AreNotEqual(datagram, random.NextDatagram(datagram.Length));
if (datagram.Length > 2)
Assert.AreNotEqual(datagram.GetHashCode(), random.NextDatagram(datagram.Length).GetHashCode());
}
else
Assert.AreEqual(datagram, Datagram.Empty);
// Check Enumerable
IEnumerable enumerable = datagram;
int offset = 0;
foreach (byte b in enumerable)
Assert.AreEqual(datagram[offset++], b);
}
}
示例2: TestPriorityQueue
public void TestPriorityQueue()
{
int operationsCount = 100000;
Random rand = new Random(0);
PriorityQueue<double> queue = new PriorityQueue<double>();
for (int op = 0; op < operationsCount; ++op)
{
int opType = rand.Next(0, 2);
if (opType == 0) // Enqueue
{
double item = (100.0 - 1.0) * rand.NextDouble() + 1.0;
queue.Enqueue(item);
Assert.IsTrue(queue.IsConsistent(), "Test fails after enqueue operation # " + op);
}
else // Dequeue
{
if (queue.Count > 0)
{
double item = queue.Dequeue();
Assert.IsTrue(queue.IsConsistent(), "Test fails after dequeue operation # " + op);
}
}
}
}
示例3: btnAddPID_Click
private void btnAddPID_Click(object sender, EventArgs e)
{
if (tbPID.EditValue == null || tbPID.EditValue.ToString().Trim() == string.Empty)
{
return;
}
if (!dxvp.Validate(ccbProxy))
return;
string[] PIDs = tbPID.EditValue.ToString().Split('\n');
string[] proxies = ccbProxy.EditValue.ToString().Split(',');
Random rnd = new Random();
foreach (string pid in PIDs)
{
if (pid.Trim() == string.Empty)
continue;
_flagList.Add(new Datasource.FlagUnit("", 0, "", pid.Trim(), "Unknown", "Unknown"));
foreach (string proxy in proxies)
{
int id = rnd.Next(0, dsData.UserAgent.Count);
Datasource.FlagUnit data = new Datasource.FlagUnit(proxy, dsData.UserAgent[id].UserAgentId, dsData.UserAgent[id].UserAgentName, pid.Trim(), "Unknown", "Unknown");
_flagQue.Enqueue(data);
gridControlPID.RefreshDataSource();
}
}
tbPID.EditValue = null;
}
示例4: User
public User(StateManager stateMgr, API.Geo.World world)
{
this.mStateMgr = stateMgr;
this.mWorld = world;
this.mTimeSinceGUIOpen = new Timer();
this.mCameraMan = null;
this.IsAllowedToMoveCam = true;
this.IsFreeCamMode = true;
Camera cam = this.mStateMgr.Camera;
cam.Position = new Vector3(-203, 633, -183);
cam.Orientation = new Quaternion(0.3977548f, -0.1096644f, -0.8781486f, -0.2421133f);
this.mCameraMan = new CameraMan(cam);
this.mSelectedAllies = new HashSet<VanillaNonPlayer>();
this.mRandom = new Random();
this.mFigures = new MOIS.KeyCode[10];
for (int i = 0; i < 9; i++)
this.mFigures[i] = (MOIS.KeyCode)System.Enum.Parse(typeof(MOIS.KeyCode), "KC_" + (i + 1));
this.mFigures[9] = MOIS.KeyCode.KC_0;
this.mWireCube = this.mStateMgr.SceneMgr.RootSceneNode.CreateChildSceneNode();
this.mWireCube.AttachObject(StaticRectangle.CreateRectangle(this.mStateMgr.SceneMgr, Vector3.UNIT_SCALE * Cst.CUBE_SIDE));
this.mWireCube.SetVisible(false);
this.Inventory = new Inventory(10, 4, new int[] { 3, 0, 1, 2 }, true);
}
示例5: ProcessRequest
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Clear();
if (context.Request.Files.Count > 0)
{
try
{
HttpPostedFile httpPostFile = context.Request.Files[0];
string file = context.Request.Form["Filename"].ToString();
string fileType = file.Substring(file.LastIndexOf('.')).ToLower();
Random r = new Random();
string fileName = DateTime.Now.ToString("yyyyMMdd-HHmmss-ms") + r.Next(100, 999) + fileType;
string serverPath = System.Configuration.ConfigurationSettings.AppSettings["ImageUploadPath"];
httpPostFile.SaveAs(context.Server.MapPath(serverPath + fileName));
context.Application["ImageUrl"] = serverPath + fileName;
context.Response.Write("UP_OK");
}
catch
{
context.Response.Write("UP_FAILE");
}
}
else
{
context.Response.Write("UP_FAILE");
}
}
示例6: Main
static void Main(string[] args)
{
const int NumberOfAnimals = 10;
Stack<Animal> animalStack = new Stack<Animal>();
Queue<Animal> animalQueue = new Queue<Animal>();
Console.WriteLine("/// ORDER OF ENTRY...");
Random r = new Random();
for (int index = 0; index < NumberOfAnimals; index++)
{
var animalShouldBeCat = (r.Next(2) == 0);
uint nextWeight = (uint)r.Next(10, 40);
Animal nextAnimal = animalShouldBeCat ? (Animal)(new Cat(nextWeight, "John")) : (Animal)(new Dog(nextWeight, "Dave"));
animalStack.Push(nextAnimal);
animalQueue.Enqueue(nextAnimal);
Console.WriteLine(nextAnimal);
}
Console.WriteLine();
Console.WriteLine("/// OUTPUT FROM STACK...");
foreach (Animal animal in animalStack)
{
Console.WriteLine(animal);
}
Console.WriteLine();
Console.WriteLine("/// OUTPUT FROM QUEUE...");
foreach (Animal animal in animalQueue)
{
Console.WriteLine(animal);
}
}
示例7: Arrange
protected void Arrange()
{
var random = new Random();
_subsystemName = random.Next().ToString(CultureInfo.InvariantCulture);
_operationTimeout = TimeSpan.FromSeconds(30);
_encoding = Encoding.UTF8;
_disconnectedRegister = new List<EventArgs>();
_errorOccurredRegister = new List<ExceptionEventArgs>();
_channelDataEventArgs = new ChannelDataEventArgs(
(uint)random.Next(0, int.MaxValue),
new[] { (byte)random.Next(byte.MinValue, byte.MaxValue) });
_sessionMock = new Mock<ISession>(MockBehavior.Strict);
_channelMock = new Mock<IChannelSession>(MockBehavior.Strict);
_sequence = new MockSequence();
_sessionMock.InSequence(_sequence).Setup(p => p.CreateChannelSession()).Returns(_channelMock.Object);
_channelMock.InSequence(_sequence).Setup(p => p.Open());
_channelMock.InSequence(_sequence).Setup(p => p.SendSubsystemRequest(_subsystemName)).Returns(true);
_subsystemSession = new SubsystemSessionStub(
_sessionMock.Object,
_subsystemName,
_operationTimeout,
_encoding);
_subsystemSession.Disconnected += (sender, args) => _disconnectedRegister.Add(args);
_subsystemSession.ErrorOccurred += (sender, args) => _errorOccurredRegister.Add(args);
_subsystemSession.Connect();
}
示例8: ChangeMatchDates
/// <summary>
/// If there is no real life data between seasons,
/// change some match dates to around now for testing purposes
/// </summary>
private static void ChangeMatchDates(TtcDbContext context)
{
bool endOfSeason = !context.Matches.Any(match => match.Date > DateTime.Now);
if (true || endOfSeason)
{
var passedMatches = context.Matches
.Where(x => x.FrenoySeason == Constants.FrenoySeason)
//.Where(x => x.Date < DateTime.Today)
.OrderByDescending(x => x.Date)
.Take(42);
var timeToAdd = DateTime.Today - passedMatches.First().Date;
foreach (var match in passedMatches.Take(20))
{
match.Date = match.Date.Add(timeToAdd);
}
var rnd = new Random();
foreach (var match in passedMatches.Take(20))
{
match.Date = DateTime.Today.Add(TimeSpan.FromDays(rnd.Next(1, 20))).AddHours(rnd.Next(10, 20));
match.Description = "";
match.AwayScore = null;
match.HomeScore = null;
//match.IsSyncedWithFrenoy = true;
match.WalkOver = false;
context.MatchComments.RemoveRange(match.Comments.ToArray());
context.MatchGames.RemoveRange(match.Games.ToArray());
context.MatchPlayers.RemoveRange(match.Players.ToArray());
}
}
}
示例9: Main
static void Main(string[] args)
{
var m_Config = new ServerConfig
{
Port = 911,
Ip = "Any",
MaxConnectionNumber = 1000,
Mode = SocketMode.Tcp,
Name = "CustomProtocolServer"
};
var m_Server = new CustomProtocolServer();
m_Server.Setup(m_Config, logFactory: new ConsoleLogFactory());
m_Server.Start();
EndPoint serverAddress = new IPEndPoint(IPAddress.Parse("127.0.0.1"), m_Config.Port);
using (Socket socket = new Socket(serverAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp))
{
socket.Connect(serverAddress);
var socketStream = new NetworkStream(socket);
var reader = new StreamReader(socketStream, Encoding.ASCII, false);
string charSource = Guid.NewGuid().ToString().Replace("-", string.Empty)
+ Guid.NewGuid().ToString().Replace("-", string.Empty)
+ Guid.NewGuid().ToString().Replace("-", string.Empty);
Random rd = new Random();
var watch = Stopwatch.StartNew();
for (int i = 0; i < 10; i++)
{
int startPos = rd.Next(0, charSource.Length - 2);
int endPos = rd.Next(startPos + 1, charSource.Length - 1);
var currentMessage = charSource.Substring(startPos, endPos - startPos + 1);
byte[] requestNameData = Encoding.ASCII.GetBytes("ECHO");
socketStream.Write(requestNameData, 0, requestNameData.Length);
var data = Encoding.ASCII.GetBytes(currentMessage);
socketStream.Write(new byte[] { (byte)(data.Length / 256), (byte)(data.Length % 256) }, 0, 2);
socketStream.Write(data, 0, data.Length);
socketStream.Flush();
// Console.WriteLine("Sent: " + currentMessage);
var line = reader.ReadLine();
//Console.WriteLine("Received: " + line);
//Assert.AreEqual(currentMessage, line);
}
watch.Stop();
Console.WriteLine(watch.ElapsedMilliseconds);
}
Console.ReadLine();
}
示例10: Main2
static void Main2(string[] args)
{
var numReal = new List<double>(80);
Random gerador = new Random();
double maior = 0;
double menor = 0;
double soma = 0;
double media = 0;
for (int i = 0; i < 80; i++)
{
numReal.Add(gerador.NextDouble());
if (i == 0)
{
maior = numReal[i];
menor = numReal[i];
}
soma += numReal[i];
}
media = soma / 80;
for (int i = 0; i < 80; i++)
{
maior = (numReal[i] > maior) ? numReal[i] : maior;
menor = (numReal[i] < menor) ? numReal[i] : menor;
}
Console.WriteLine("Maior: {0:F2}", maior);
Console.WriteLine("Menor: {0:F2}", menor);
Console.WriteLine("Soma: {0:F2}", soma);
Console.WriteLine("Media: {0:F2}", media);
Console.ReadKey();
}
示例11: ApplySetPieces
public static void ApplySetPieces(World world)
{
var map = world.Map;
int w = map.Width, h = map.Height;
Random rand = new Random();
HashSet<Rect> rects = new HashSet<Rect>();
foreach (var dat in setPieces)
{
int size = dat.Item1.Size;
int count = rand.Next(dat.Item2, dat.Item3);
for (int i = 0; i < count; i++)
{
IntPoint pt = new IntPoint();
Rect rect;
int max = 50;
do
{
pt.X = rand.Next(0, w);
pt.Y = rand.Next(0, h);
rect = new Rect() { x = pt.X, y = pt.Y, w = size, h = size };
max--;
} while ((Array.IndexOf(dat.Item4, map[pt.X, pt.Y].Terrain) == -1 ||
rects.Any(_ => Rect.Intersects(rect, _))) &&
max > 0);
if (max <= 0) continue;
dat.Item1.RenderSetPiece(world, pt);
rects.Add(rect);
}
}
}
示例12: Initialise
public void Initialise()
{
_primitives = new List<Cube>();
var random = new Random();
for (int i = 0; i < Constants.CubeCount; i++)
{
_primitives.Add(new Cube
{
Color = Color.Red,
Position = new Vector3(random.Next(100) - 50, random.Next(100) - 50, -random.Next(100)),
Radius = random.Next(100),
Rotation = Vector3.Zero
});
}
//How to create a kernel and a channel?
// _kernel =
// _channel =
_colour = Color.Beige;
_kernel.Factory.NewCoroutine(ChangePosition);
_kernel.Factory.NewCoroutine(ChangeColour);
}
示例13: GetReady
public void GetReady ()
{
dataTable = new DataTable ("itemTable");
dc1 = new DataColumn ("itemId");
dc2 = new DataColumn ("itemName");
dc3 = new DataColumn ("itemPrice");
dc4 = new DataColumn ("itemCategory");
dataTable.Columns.Add (dc1);
dataTable.Columns.Add (dc2);
dataTable.Columns.Add (dc3);
dataTable.Columns.Add (dc4);
DataRow dr;
seed = 123;
rowCount = 5;
rndm = new Random (seed);
for (int i = 1; i <= rowCount; i++) {
dr = dataTable.NewRow ();
dr["itemId"] = "item " + i;
dr["itemName"] = "name " + rndm.Next ();
dr["itemPrice"] = "Rs. " + (rndm.Next () % 1000);
dr["itemCategory"] = "Cat " + ((rndm.Next () % 10) + 1);
dataTable.Rows.Add (dr);
}
dataTable.AcceptChanges ();
dataView = new DataView (dataTable);
dataView.ListChanged += new ListChangedEventHandler (OnListChanged);
listChangedArgs = null;
}
示例14: TestConcurrentQueueDeclare
public void TestConcurrentQueueDeclare()
{
string x = GenerateExchangeName();
Random rnd = new Random();
List<Thread> ts = new List<Thread>();
System.NotSupportedException nse = null;
for(int i = 0; i < 256; i++)
{
Thread t = new Thread(() =>
{
try
{
// sleep for a random amount of time to increase the chances
// of thread interleaving. MK.
Thread.Sleep(rnd.Next(5, 500));
Model.ExchangeDeclare(x, "fanout", false, false, null);
} catch (System.NotSupportedException e)
{
nse = e;
}
});
ts.Add(t);
t.Start();
}
foreach (Thread t in ts)
{
t.Join();
}
Assert.IsNotNull(nse);
Model.ExchangeDelete(x);
}
示例15: ViewModel
public ViewModel()
{
mgt = new ManagementClass("Win32_Processor");
procs = mgt.GetInstances();
CPU = new ObservableCollection<Model>();
timer = new DispatcherTimer();
random = new Random();
time = DateTime.Now;
cpuCounter = new PerformanceCounter();
cpuCounter.CategoryName = "Processor";
cpuCounter.CounterName = "% Processor Time";
cpuCounter.InstanceName = "_Total";
ramCounter = new PerformanceCounter("Memory", "Available MBytes");
ProcessorID = GetProcessorID();
processes = Process.GetProcesses();
Processes = processes.Length;
MaximumSpeed = GetMaxClockSpeed();
LogicalProcessors = GetNumberOfLogicalProcessors();
Cores = GetNumberOfCores();
L2Cache = GetL2CacheSize();
L3Cache = GetL3CacheSize();
foreach (ManagementObject item in procs)
L1Cache = ((UInt32)item.Properties["L2CacheSize"].Value / 2).ToString() + " KB";
timer.Interval = TimeSpan.FromMilliseconds(1000);
timer.Tick += timer_Tick;
timer.Start();
for (int i = 0; i < 60; i++)
{
CPU.Add(new Model(time, 0,0));
time = time.AddSeconds(1);
}
}