本文整理汇总了C#中FastRandom.Next方法的典型用法代码示例。如果您正苦于以下问题:C# FastRandom.Next方法的具体用法?C# FastRandom.Next怎么用?C# FastRandom.Next使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类FastRandom
的用法示例。
在下文中一共展示了FastRandom.Next方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: GetRandomVectors
private IEnumerable<List<int>> GetRandomVectors(int n, FastRandom rand) {
for (int i = 0; i < n; i++) {
int length = rand.Next(1, 50);
List<int> cur = new List<int>(length) { 0 };
for (int j = 0; j < length - 1; j++) {
cur.Add(rand.Next(-50, 50));
}
yield return cur.Shuffle(rand).ToList();
}
}
示例2: MsgKeepAlive
public MsgKeepAlive()
: base()
{
FastRandom fastRand = new FastRandom();
this.Payload = new byte[fastRand.Next(32, 256)];
fastRand.NextBytes(this.Payload);
}
示例3: Problem
public Problem()
: base() {
Parameters.Add(new FixedValueParameter<IntValue>(LawnWidthParameterName, "Width of the lawn.", new IntValue(8)));
Parameters.Add(new FixedValueParameter<IntValue>(LawnLengthParameterName, "Length of the lawn.", new IntValue(8)));
var g = new SimpleSymbolicExpressionGrammar();
g.AddSymbols(new string[] { "Sum", "Prog" }, 2, 2);
g.AddSymbols(new string[] { "Frog" }, 1, 1);
g.AddTerminalSymbols(new string[] { "Left", "Forward" });
// initialize 20 ephemeral random constants in [0..32[
var fastRand = new FastRandom(314159);
for (int i = 0; i < 20; i++) {
g.AddTerminalSymbol(string.Format("{0},{1}", fastRand.Next(0, 32), fastRand.Next(0, 32)));
}
Encoding = new SymbolicExpressionTreeEncoding(g, 1000, 17);
}
示例4: OnGetPaletteToCache
/// <summary>
/// See <see cref="BaseColorCacheQuantizer.OnGetPaletteToCache"/> for more details.
/// </summary>
protected override List<Color> OnGetPaletteToCache(Int32 colorCount)
{
// use fast random class
FastRandom random = new FastRandom(0);
// NOTE: I've added a little randomization here, as it was performing terribly otherwise.
// sorts out the list by a pixel presence, takes top N slots, and calculates
// the average color from them, thus our new palette.
IEnumerable<Color> colors = colorMap.
OrderBy(entry => random.Next(colorMap.Count)).
OrderByDescending(entry => entry.Value.PixelCount).
Take(colorCount).
Select(entry => entry.Value.GetAverage());
palette.Clear();
palette.AddRange(colors);
return palette;
}
示例5: SetSpawnPosition
public override void SetSpawnPosition (Vector3 playerSpawn, PhysicsComponent ownPhysics, object map, FastRandom rand)
{
Maze.Maze maze = map as Maze.Maze;
if (maze != null)
{
bool gotit = false;
while (!gotit)
{
int pos = rand.Next (0, maze.graph.Nodes.Count);
Vector3 spawn_pos;
float distance;
for (int i = pos; i < maze.graph.Nodes.Count; i++)
{
spawn_pos = maze.graph.Nodes[i].Data.WorldPosition;
Vector3.Distance(ref playerSpawn, ref spawn_pos, out distance);
if (maze.graph.Nodes[i].Data.MazeCellType == MazeCellType.Ground && distance > 50 &&
!maze.graph.Nodes[i].Data.IsExit)
{
gotit = true;
ownPhysics.RigidBody.Position = new JVector (maze.graph.Nodes[i].Data.WorldPosition.X, height,
maze.graph.Nodes[i].Data.WorldPosition.Z);
break;
}
}
}
if (!gotit)
{
Logger.Log.AddLogEntry (LogLevel.Severe, "GhostAI", "Failed to generate spawn position!");
}
fallback = JVector.Transform (JVector.Backward, JMatrix.CreateFromAxisAngle (JVector.Up,
(float) rand.NextDouble() * 2 * MathHelper.Pi));
direction = fallback;
Spawned = true;
}
}
示例6: ProcessPayload
public override void ProcessPayload(SSPClient client, OperationalSocket _OpSocket)
{
RequestHeader reqHeader = Header as RequestHeader;
if (reqHeader != null)
{
Type type = null;
lock (client.Connection.RegisteredOperationalSockets)
{
client.Connection.RegisteredOperationalSockets.TryGetValue(Identifier, out type);
}
if(type != null)
{
bool SendedSuccess = false;
try
{
OperationalSocket OpSocket = (OperationalSocket)Activator.CreateInstance(type, client);
OpSocket.isConnected = true;
lock (client.Connection.OperationalSockets)
{
FastRandom rnd = new FastRandom();
OpSocket.ConnectionId = (ushort)rnd.Next(1, 65535);
while(client.Connection.OperationalSockets.ContainsKey(OpSocket.ConnectionId))
OpSocket.ConnectionId = (ushort)rnd.Next(1, 65535);
client.Connection.OperationalSockets.Add(OpSocket.ConnectionId, OpSocket);
}
try
{
OpSocket.onBeforeConnect();
client.onOperationalSocket_BeforeConnect(OpSocket);
}
catch (Exception ex)
{
SysLogger.Log(ex.Message, SysLogType.Error);
OpSocket.onException(ex, ErrorType.UserLand);
}
client.Connection.SendMessage(new MsgCreateConnectionResponse(OpSocket.ConnectionId, true), new RequestHeader(reqHeader.RequestId, true));
SendedSuccess = true;
OpSocket.onConnect();
client.onOperationalSocket_Connected(OpSocket);
}
catch (Exception ex)
{
SysLogger.Log(ex.Message, SysLogType.Error);
if (!SendedSuccess)
{
client.Connection.SendMessage(new MsgCreateConnectionResponse(0, false), new RequestHeader(reqHeader.RequestId, true));
}
}
}
else
{
client.Connection.SendMessage(new MsgCreateConnectionResponse(0, false), new RequestHeader(reqHeader.RequestId, true));
}
}
}
示例7: morphEnglish
static Dictionary<string, double> morphEnglish(Dictionary<string, double> english, double[] digitProbs, double[] posProbs, int minLength = 0)
{
Dictionary<string, double> results = new Dictionary<string, double>();
FastRandom random = new FastRandom();
Console.WriteLine("Probs sum: {0}", digitProbs.Sum());
RouletteWheelLayout digitLayout = new RouletteWheelLayout(digitProbs);
RouletteWheelLayout posLayout = new RouletteWheelLayout(posProbs);
int alreadyNumbered = 0;
foreach (string s in english.Keys)
{
bool numbered = false;
for (int i = 0; i < s.Length; i++)
if (s[i] >= '0' && s[i] <= '9')
{
alreadyNumbered++;
numbered = true;
break;
}
string morphedPassword = s;
while (!numbered || morphedPassword.Length < minLength)
{
int toAdd = RouletteWheel.SingleThrow(digitLayout, random);
int pos = RouletteWheel.SingleThrow(posLayout, random);
if (pos == 0)
break;
else if (pos == 1)
morphedPassword = toAdd + morphedPassword;
else if (pos == 2)
morphedPassword = morphedPassword + toAdd;
else
{
pos = random.Next(morphedPassword.Length);
morphedPassword = morphedPassword.Substring(0, pos) + toAdd + morphedPassword.Substring(pos, morphedPassword.Length - pos);
}
numbered = true;
}
double val;
if (!results.TryGetValue(morphedPassword, out val))
results.Add(morphedPassword, 1);
}
Console.WriteLine("Had numbers already: {0}", alreadyNumbered);
return results;
}
示例8: CreateCoevolutionAlgorithmContainer
/// <summary>
/// Creates the evolution algorithm container using the given factories and genome lists.
/// </summary>
/// <param name="genomeFactory1">The agent genome factory.</param>
/// <param name="genomeFactory2">The maze genome factory.</param>
/// <param name="genomeList1">The agent genome list.</param>
/// <param name="genomeList2">The maze genome list.</param>
/// <returns>The instantiated coevolution algorithm container.</returns>
public override ICoevolutionAlgorithmContainer<NeatGenome, MazeGenome> CreateCoevolutionAlgorithmContainer(
IGenomeFactory<NeatGenome> genomeFactory1,
IGenomeFactory<MazeGenome> genomeFactory2, List<NeatGenome> genomeList1, List<MazeGenome> genomeList2)
{
List<NeatGenome> seedAgentPopulation = new List<NeatGenome>();
// Compute the maze max complexity
((MazeGenomeFactory) genomeFactory2).MaxComplexity = MazeUtils.DetermineMaxPartitions(_mazeHeight,
_mazeWidth, 200);
// Create maze decoder to decode initialization mazes
MazeDecoder mazeDecoder = new MazeDecoder(_mazeHeight, _mazeWidth, _mazeScaleMultiplier);
// Loop through every maze and evolve the requisite number of viable genomes that solve it
for (int idx = 0; idx < genomeList2.Count; idx++)
{
Console.WriteLine(@"Evolving viable agents for maze population index {0} and maze ID {1}", idx,
genomeList2[idx].Id);
// Evolve the number of agents required to meet the success MC for the current maze
List<NeatGenome> viableMazeAgents = EvolveViableAgents(genomeFactory1, genomeList1.ToList(),
mazeDecoder.Decode(genomeList2[idx]));
// Add the viable agent genomes who solve the current maze (but avoid adding duplicates, as identified by the genome ID)
// Note that it's fine to have multiple mazes solved by the same agent, so in this case, we'll leave the agent
// in the pool of seed agent genomes
foreach (
NeatGenome viableMazeAgent in
viableMazeAgents.Where(
viableMazeAgent =>
seedAgentPopulation.Select(sap => sap.Id).Contains(viableMazeAgent.Id) == false))
{
seedAgentPopulation.Add(viableMazeAgent);
}
}
// If we still lack the genomes to fill out agent specie count while still satisfying the maze MC,
// iteratively pick a random maze and evolve agents on that maze until we reach the requisite number
while (seedAgentPopulation.ToList().Count < _numAgentSuccessCriteria*AgentNumSpecies)
{
FastRandom rndMazePicker = new FastRandom();
// Pick a random maze on which to evolve agent(s)
MazeGenome mazeGenome = genomeList2[rndMazePicker.Next(genomeList2.Count - 1)];
Console.WriteLine(
@"Continuing viable agent evolution on maze {0}, with {1} of {2} required agents in place",
mazeGenome.Id, seedAgentPopulation.Count, (_numAgentSuccessCriteria*AgentNumSpecies));
// Evolve the number of agents required to meet the success MC for the maze
List<NeatGenome> viableMazeAgents = EvolveViableAgents(genomeFactory1, genomeList1.ToList(),
mazeDecoder.Decode(mazeGenome));
// Iterate through each viable agent and remove them if they've already solved a maze or add them to the list
// of viable agents if they have not
foreach (NeatGenome viableMazeAgent in viableMazeAgents)
{
// If they agent has already solved maze and is in the list of viable agents, remove that agent
// from the pool of seed genomes (this is done because here, we're interested in getting unique
// agents and want to avoid an endless loop wherein the same viable agents are returned)
if (seedAgentPopulation.Select(sap => sap.Id).Contains(viableMazeAgent.Id))
{
genomeList1.Remove(viableMazeAgent);
}
// Otherwise, add that agent to the list of viable agents
else
{
seedAgentPopulation.Add(viableMazeAgent);
}
}
}
// Set dummy fitness so that seed maze(s) will be marked as evaluated
foreach (MazeGenome mazeGenome in genomeList2)
{
mazeGenome.EvaluationInfo.SetFitness(0);
}
// Reset primary NEAT genome parameters on agent genome factory
((NeatGenomeFactory) genomeFactory1).ResetNeatGenomeParameters(NeatGenomeParameters);
// Create the NEAT (i.e. navigator) queueing evolution algorithm
AbstractEvolutionAlgorithm<NeatGenome> neatEvolutionAlgorithm =
new MultiQueueNeatEvolutionAlgorithm<NeatGenome>(
new NeatEvolutionAlgorithmParameters
{
SpecieCount = AgentNumSpecies,
MaxSpecieSize = AgentDefaultPopulationSize/AgentNumSpecies
},
new ParallelKMeansClusteringStrategy<NeatGenome>(new ManhattanDistanceMetric(1.0, 0.0, 10.0),
ParallelOptions), null, NavigatorBatchSize, RunPhase.Primary, _navigatorEvolutionDataLogger,
_navigatorLogFieldEnableMap, _navigatorPopulationGenomesDataLogger, _populationLoggingBatchInterval);
//.........这里部分代码省略.........
示例9: RegisterRequest
internal SyncObject RegisterRequest(ref int RequestId)
{
lock (Requests)
{
SyncObject syncObj = new SyncObject(this);
FastRandom rnd = new FastRandom();
do
{
RequestId = rnd.Next();
}
while (Requests.ContainsKey(RequestId));
Requests.Add(RequestId, syncObj);
return syncObj;
}
}
示例10: PreviewSplatFilm
private void PreviewSplatFilm(IFilmFrame frame, int curY = -1, int pixelsInPreview = 10000)
{
var bmpWidth = frame.Width;
var bmpHeight = (curY > 0 ? curY : frame.Height);
var rnd = new FastRandom();
RgbSpectrum.Gamma = true;
for (int n = 0; n < pixelsInPreview; n++)
//for (int i = 0; i < bmpHeight; i++)
{
//for (int j = 0; j < bmpWidth; j++)
{
var i = rnd.Next(0, bmpHeight);
var j = rnd.Next(0, bmpWidth);
var pixOffset = frame.Width * ((bmpHeight - i - 1)) + j;
var color = ((frame.Data[pixOffset] / frame.Weight[pixOffset])).Transform();
this.imagePlane.Data[pixOffset] = color;
}
}
}
示例11: ShuffleValues
private void ShuffleValues(byte[] values, int Seed)
{
FastRandom rnd = new FastRandom(Seed);
for (int i = values.Length, j = 0; i > 1; i--, j++)
{
int pos = rnd.Next(i);
byte tmp = values[pos];
values[pos] = values[i - 1];
values[i - 1] = tmp;
}
}
示例12: MazeTest
//.........这里部分代码省略.........
AddAudio (state);
// embed new maze into game state logic and create a MoveEntityToScene
SkyboxSystem.CreateSkybox (state.Scene, Player);
Player.GetComponent<TransformComponent> ().Position = new Vector3 (0, 1.85f, 0);
var maze_cam_entity = EntityFactory.Instance.CreateWith ("maze_cam_transform", state.MessageProxy, new[] { typeof(TransformComponent) });
var maze_cam_transform = maze_cam_entity.GetComponent<TransformComponent> ();
var maze_cam = new BaseCamera (maze_cam_entity, state.MessageProxy, orthographic: true);
state.Scene.CameraManager.AddCamera (maze_cam, "maze");
maze_cam_transform.Position = new Vector3 (115, 240, 110);
maze_cam_transform.Rotation = Quaternion.FromAxisAngle (Vector3.UnitX, MathHelper.PiOver2);
state.Scene.CameraManager.AddCamera (new BaseCamera (Player, state.MessageProxy), "player");
RigidBody playerBody = new RigidBody (new SphereShape (1f));
playerBody.Position = Player.GetComponent<TransformComponent> ().Position.ToJitterVector ();
playerBody.AllowDeactivation = false;
playerBody.Material.StaticFriction = 0f;
playerBody.Material.KineticFriction = 0f;
playerBody.Material.Restitution = 0.1f;
//playerBody.Mass = 1000000.0f;
playerBody.Update ();
Player.GetComponent<PhysicsComponent> ().RigidBody = playerBody;
Player.GetComponent<PhysicsComponent> ().World = state.PhysicsManager.World;
Player.GetComponent<PhysicsComponent> ().PhysicsApplying = AffectedByPhysics.Position;
#if PRESENTATION
Player.GetComponent<HealthComponent>().MaximumHealth = 500;
Player.GetComponent<HealthComponent>().Health = 500;
#endif
state.PhysicsManager.World.AddBody (playerBody);
int seed = new FastRandom ().Next ();
var rand = new FastRandom (seed);
Logger.Log.AddLogEntry (LogLevel.Debug, "MazeTest", "Seed: {0}", seed);
#if PRESENTATION
maze [0] = mazeGenerator.CreateMaze<OverworldMazeTheme> (rand.Next (), state.MessageProxy, state.PhysicsManager, app.AudioManager, 10, 10);
#else
maze [0] = mazeGenerator.CreateMaze<OverworldMazeTheme> (rand.Next (), state.MessageProxy, state.PhysicsManager, app.AudioManager, 30, 30);
#endif
maze [0].PlayerPosition += Player.GetComponent<TransformComponent> ().Position;
maze [0].AIManager.RegisterEntity (Player);
for (int i = 0; i < OverworldScobisCount; i++)
{
ScobisInstances.Add (new Scobis (state, maze [0].AIManager, rendererContext));
}
for (int i = 0; i < OverworldCaligoCount; i++)
{
CaligoInstances.Add (new Caligo (state, maze [0].AIManager, rendererContext, warpingNode));
}
for (int i = 0; i < OverworldViridionCount; i++)
{
ViridionInstances.Add (new Viridion (state, maze [0].AIManager, rendererContext, ColorCorrectionNode));
}
for (int i = 0; i < OverworldGhostCount; i++)
{
GhostInstances.Add (new Ghost (state, maze [0].AIManager, rendererContext, ColorCorrectionNode));
}
game.AddGameState ("maze_underworld", Content.Environment.Default,
示例13: SampleTriangleIndex
private int SampleTriangleIndex(FastRandom rnd)
{
return rnd.Next(0, triangleSampleData.Length - 1);
}
示例14: ShuffleInstructions
private void ShuffleInstructions(InstructionInfo[] insts, int Seed)
{
FastRandom rnd = new FastRandom(Seed);
for (int i = insts.Length, j = 0; i > 1; i--, j++)
{
int pos = rnd.Next(i); // 0 <= j <= i-1
InstructionInfo tmp = insts[pos];
insts[pos] = insts[i - 1];
insts[i - 1] = tmp;
}
}
示例15: GetNextRandomInstruction
private static void GetNextRandomInstruction(FastRandom rnd, ref InstructionInfo EncInstruction, ref InstructionInfo DecInstruction)
{
lock (RndInstLock)
{
Instruction[] InstructionList = new Instruction[]
{
//Instruction.BitLeft, //unstable do not use
Instruction.Minus,
Instruction.Plus,
//Instruction.ForLoop_PlusMinus,
//Instruction.RotateLeft_Big,
//Instruction.RotateLeft_Small,
Instruction.SwapBits,
Instruction.XOR
};
Instruction inst = InstructionList[rnd.Next(0, InstructionList.Length)];
switch (inst)
{
case Instruction.BitLeft:
{
int bitSize = rnd.Next(1, 3); //maybe needs to be higher ?
EncInstruction = new InstructionInfo(inst, bitSize);
DecInstruction = new InstructionInfo(Instruction.BitRight, bitSize);
break;
}
case Instruction.Minus:
{
byte[] TempDate = new byte[32];
rnd.NextBytes(TempDate);
EncInstruction = new InstructionInfo(inst, new BigInteger(TempDate));
DecInstruction = new InstructionInfo(Instruction.Plus, new BigInteger(TempDate));
break;
}
case Instruction.Plus:
{
byte[] TempDate = new byte[32];
rnd.NextBytes(TempDate);
EncInstruction = new InstructionInfo(inst, new BigInteger(TempDate));
DecInstruction = new InstructionInfo(Instruction.Minus, new BigInteger(TempDate));
break;
}
case Instruction.ForLoop_PlusMinus:
{
int size = rnd.Next();
int size2 = rnd.Next();
int loops = rnd.Next(2, 255);
EncInstruction = new InstructionInfo(inst, (uint)size, (uint)size2, loops);
DecInstruction = new InstructionInfo(inst, (uint)size, (uint)size2, loops);
break;
}
case Instruction.RotateLeft_Big:
{
byte bitSize = (byte)rnd.Next(1, 60);
EncInstruction = new InstructionInfo(inst, (uint)bitSize);
DecInstruction = new InstructionInfo(Instruction.RotateRight_Big, (uint)bitSize);
break;
}
case Instruction.RotateLeft_Small:
{
byte bitSize = (byte)rnd.Next(1, 30);
EncInstruction = new InstructionInfo(inst, (uint)bitSize);
DecInstruction = new InstructionInfo(Instruction.RotateRight_Small, (uint)bitSize);
break;
}
case Instruction.SwapBits:
{
EncInstruction = new InstructionInfo(inst, 0);
DecInstruction = new InstructionInfo(inst, 0);
break;
}
case Instruction.XOR:
{
byte[] TempDate = new byte[32];
rnd.NextBytes(TempDate);
EncInstruction = new InstructionInfo(inst, new BigInteger(TempDate));
DecInstruction = new InstructionInfo(inst, new BigInteger(TempDate));
break;
}
default: { break; }
}
}
}