/// <summary> /// Generates a slightly randomized expression. /// </summary> static BoolExpr MkRandomExpr(Context ctx, System.Random rng) { int limit = 1073741823; Sort i = ctx.IntSort; Sort b = ctx.BoolSort; Symbol sr1 = ctx.MkSymbol(rng.Next(0, limit)); Symbol sr2 = ctx.MkSymbol(rng.Next(0, limit)); Symbol sr3 = ctx.MkSymbol(rng.Next(0, limit)); FuncDecl r1 = ctx.MkFuncDecl(sr1, i, b); FuncDecl r2 = ctx.MkFuncDecl(sr2, i, b); FuncDecl r3 = ctx.MkFuncDecl(sr3, i, b); Symbol s = ctx.MkSymbol(rng.Next(0, limit)); Expr x = ctx.MkConst(s, i); BoolExpr r1x = (BoolExpr)ctx.MkApp(r1, x); BoolExpr r2x = (BoolExpr)ctx.MkApp(r2, x); BoolExpr r3x = (BoolExpr)ctx.MkApp(r3, x); Expr[] vars = { x }; BoolExpr rl1 = ctx.MkForall(vars, ctx.MkImplies(r1x, r2x)); BoolExpr rl2 = ctx.MkForall(vars, ctx.MkImplies(r2x, r1x)); BoolExpr rl3 = (BoolExpr)ctx.MkApp(r1, ctx.MkInt(3)); BoolExpr q = (BoolExpr)ctx.MkApp(r3, ctx.MkInt(2)); BoolExpr a1 = ctx.MkNot(q); BoolExpr q1 = ctx.MkExists(vars, ctx.MkAnd(r3x, r2x)); BoolExpr q2 = ctx.MkExists(vars, ctx.MkAnd(r3x, r1x)); BoolExpr[] all = { a1, q1, q2 }; return ctx.MkAnd(all); }
public string GetNextName(int? count, Gender gender, bool animal, System.Random randomNumber) { //sets an internal counter and escape count = (count ?? 0); if (count == 50) { return ""; } string freshName = ""; if (animal) { return animalNames[randomNumber.Next(0, animalNames.Count)]; } else { freshName = gender == Gender.Female ? femaleNames[randomNumber.Next(0, femaleNames.Count)] : maleNames[randomNumber.Next(0, maleNames.Count)]; freshName += " " + lastNames[randomNumber.Next(0, lastNames.Count)]; } if (usedNames.Contains(freshName)) { return GetNextName(count + 1, gender, animal, randomNumber); } else { usedNames.Add(freshName); return freshName; } }
/*******************************/ /// <summary> /// Creates a new positive random number /// </summary> /// <param name="random">The last random obtained</param> /// <returns>Returns a new positive random number</returns> public static long NextLong(System.Random random) { long temporaryLong = random.Next(); temporaryLong = (temporaryLong << 32)+ random.Next(); if (random.Next(-1,1) < 0) return -temporaryLong; else return temporaryLong; }
/* End DEBUG ~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~ */ /// <summary> /// Stars have three sections, the base and two ring colors /// </summary> /// <param name="sourceRNG"></param> public void RandomizeSystemStar(ref System.Random sourceRNG) { //ShowLayers(true); Color c1; Color c2; Color baseColor = Color.white; float r = 0.5f; float g = 0.5f; float b = 0.5f; switch (sourceRNG.Next(1, 3)) { case 1: // Red r = sourceRNG.Next(100, 255)/255f; g = sourceRNG.Next(0, 50)/255f; b = sourceRNG.Next(0, 50)/255f; baseColor = new Color(r, g, b); break; case 2: // Blue r = sourceRNG.Next(0, 50) / 255f; g = sourceRNG.Next(0, 50) / 255f; b = sourceRNG.Next(100, 255) / 255f; baseColor = new Color(r, g, b); break; case 3: // yellow r = sourceRNG.Next(150, 255) / 255f; g = sourceRNG.Next(150, 255) / 255f; b = sourceRNG.Next(0, 50) / 255f; baseColor = new Color(r, g, b); break; } c1 = new Color( r + (float)sourceRNG.NextGaussian(0, .1), g + (float)sourceRNG.NextGaussian(0, .1), b + (float)sourceRNG.NextGaussian(0, .1) ); c2 = new Color( r + (float)sourceRNG.NextGaussian(0, .1), g + (float)sourceRNG.NextGaussian(0, .1), b + (float)sourceRNG.NextGaussian(0, .1) ); // Set up colors BaseColor = baseColor; _spriteLayers[0].color = c1; _spriteLayers[1].color = c2; }
public static IList Shuffle(IList S, System.Random R, bool Copy) { // if(S.Rank>1) // throw new Exception("Shuffle only defined on one-dimensional arrays!"); IList E; E = S; if(Copy) { if(S is ICloneable) E = ((ICloneable)S).Clone() as IList; else throw new Exception("You want it copied, but it can't!"); } int i,r; object Temp; for(i=0;i<E.Count-1;i++) { r = i+R.Next(E.Count-i); if(r==i) continue; Temp = E[i]; E[i] = E[r]; E[r] = Temp; } return E; }
public static void TestPQ(int count, System.Random gen) { PriorityQueue pq = new IntegerQueue(count); int sum = 0, sum2 = 0; for (int i = 0; i < count; i++) { int next = gen.Next(); sum += next; pq.Put((System.Object) next); } // Date end = new Date(); // System.out.print(((float)(end.getTime()-start.getTime()) / count) * 1000); // System.out.println(" microseconds/put"); // start = new Date(); int last = System.Int32.MinValue; for (int i = 0; i < count; i++) { System.Int32 next = (System.Int32) pq.Pop(); Assert.IsTrue(next >= last); last = next; sum2 += last; } Assert.AreEqual(sum, sum2); // end = new Date(); // System.out.print(((float)(end.getTime()-start.getTime()) / count) * 1000); // System.out.println(" microseconds/pop"); }
public Culture(int peopleAvailable, System.Random randomSeed) { population = Mathf.Min(randomSeed.Next(10, 101), peopleAvailable); if (peopleAvailable - population < 10) population = peopleAvailable; for (int i = 0; i < 5; i++) { int balancePoint = randomSeed.Next(4); if (balancePoint == 0) religion++; else if (balancePoint == 1) science++; else if (balancePoint == 2) art++; else if (balancePoint == 3) economy++; } if (religion >= 3) government = governmentType.theocracy; else if (science >= 3) government = governmentType.technocracy; else if (art >= 3) government = governmentType.geniocracy; else if (economy >= 3) government = governmentType.bankocracy; else { int randGovernment = randomSeed.Next(3); if (randGovernment == 0) government = governmentType.monarchy; else if (randGovernment == 1) government = governmentType.republic; else if (randGovernment == 2) government = governmentType.aristocracy; } string[] governmentString = new string[] {"republic", "monarchy", "aristocracy", "theocracy", "technocracy", "geniocracy", "bankocracy"}; int randSociability = randomSeed.Next(3); if (randSociability == 0) sociability = culturalSociability.cautious; else if (randSociability == 1) sociability = culturalSociability.neautral; else if (randSociability == 2) sociability = culturalSociability.friendly; string[] socialString = new string[] {"cautious", "neautral", "friendly"}; Debug.Log("CULTURE " + "\npopulation: " + population + "\nbalance of cultural aspects:" + "\n religion: " + religion*20 + "%" + "\n science: " + science*20 + "%" + "\n art: " + art*20 + "%" + "\n economy: " + economy*20 + "%" + "\ngovernment: " + governmentString[(int)government] + "\nsociability: " + socialString[(int)sociability]); }
private List<int> DefineOrbits(GameObject sector, System.Random gen, Vector3 starPos, int starRadius) { List<int> orbits = new List<int>(); // Calculate distance from star to origin of sector float distBorder = Vector3.Distance (starPos, sector.transform.position); // Define orbit radius so that the planets wont collide with the star and so they dont go too far outside of the sector int minOrbit = starRadius + Mathf.CeilToInt(StarToPlanetDistanceFactor * PlanetRadiusMax); int maxOrbit = (int)distBorder - PlanetRadiusMax; // Only add planets if there is enough space between the star and the border of the sector if(minOrbit < maxOrbit) { // Keep generating orbits until the "spawn check" fails bool noSpace = false; while(gen.Next(0, RandomNumberMax) < PlanetLikelihood && !noSpace) { noSpace = true; for(int n = 0; n < MaxSpawnAttempts; ++n) { int newOrbit = gen.Next(minOrbit, maxOrbit); // Make sure planets inside the same planetary system dont collide with each other bool valid = true; foreach(int otherOrbit in orbits) { if((otherOrbit < newOrbit && otherOrbit + PlanetToPlanetDistanceFactor * PlanetRadiusMax > newOrbit - PlanetRadiusMax) || (otherOrbit > newOrbit && otherOrbit - PlanetToPlanetDistanceFactor * PlanetRadiusMax < newOrbit + PlanetRadiusMax)) { valid = false; break; } } // If the orbit is valid, add it to the star's list of orbits if(valid) { orbits.Add(newOrbit); noSpace = false; break; } } } } return orbits; }
public static int getRandomValueForProperty( System.Random rand , ValueProperty prop ) { int result= 1; switch (prop) { case ValueProperty.PrimeNumber: do { result = 1 + rand.Next() % 99; } while (Utility.isPrime(result)); break; case ValueProperty.DividedBy4: result = rand.Next() % 95 + 4; result = 4 * (result / 4); break; case ValueProperty.DSumIsBiggerThan10: while (true) { int DO = 1 + rand.Next() % 9; int DT = rand.Next() % 10; result = 10 * DT + DO; if (DO + DT > 10) break; } break; case ValueProperty.DOIsBiggerThanDT: while (true) { int DO = 1 + rand.Next() % 9; int DT = rand.Next() % 10; result = 10 * DT + DO; if (DO > DT) break; } break; } return result; }
/// <summary> /// This function initialises the basic particle. /// </summary> /// <param name="rand"></param> public override void Intialise(System.Random rand) { position.Set(0, 0, 0); velocity.Set(0, 0, 0); color.R = rand.Next(256) / 256.0f; color.G = rand.Next(1) / 256.0f; color.B = rand.Next(1) / 256.0f; life = (rand.Next(100) / 1000.0f) + 0.03f; direction.X += rand.Next(10) / 100.0f; direction.Y += rand.Next(10) / 100.0f; direction.Z += rand.Next(10) / 100.0f; }
public static int randomWithProbabilityTable(System.Random random, int[] probabilityTable) { int sumProbabilities = 0; int[] probabilities = new int[probabilityTable.Length]; for (int i = 0; i < probabilityTable.Length; i++) { sumProbabilities += probabilityTable[i]; probabilities[i] += sumProbabilities; } int result = random.Next(0, sumProbabilities + 1); for (int i = 0; i < probabilityTable.Length; i++) { if (result < probabilities[i]) return i; } return 0; }
public static int randomWithProbabilityTable(System.Random random, int min, int max, int[] probabilityTable) { int sumProbabilities = 0; int[] probabilities = new int[max + 1]; for (int i = min; i <= max; i++) { sumProbabilities += probabilityTable[i]; probabilities[i] += sumProbabilities; } int result = random.Next(0, sumProbabilities + 1); for (int i = min; i <= max; i++) { if (result < probabilities[i]) return i; } return min; }
/// <summary> /// Spintx implementaion /// </summary> /// <param name="random">Random with set range</param> /// <param name="stringToModify">string to interperet</param> /// <returns>Full spingtax of text</returns> public string SpintaxParse(System.Random random, string stringToModify) { if (!stringToModify.Contains("{")) return stringToModify; var closingBracePosition = stringToModify.IndexOf('}'); var openingBracePosition = closingBracePosition; while (!stringToModify[openingBracePosition].Equals('{')) openingBracePosition--; var spintaxBlock = stringToModify.Substring(openingBracePosition, closingBracePosition - openingBracePosition + 1); var items = spintaxBlock.Substring(1, spintaxBlock.Length - 2).Split('|'); stringToModify = stringToModify.Replace(spintaxBlock, items[random.Next(items.Length)]); return SpintaxParse(random, stringToModify); }
public int OnRadiation(double energy, int count, System.Random random) { #if QUITEDEBUG Logging.Log(String.Format("{0} struck by {1:D} rays of energy {2:G}", part.partInfo.title, count, energy), false); #endif if (part.CrewCapacity > 0) { int target = random.Next(part.CrewCapacity); foreach(ProtoCrewMember cm in part.protoModuleCrew) { if (cm.seatIdx == target) { KerbalTracker kt = Core.Instance.getKT(cm); count = kt.OnRadiation(energy, count); } } } return count; }
public UISourceWindow(RadioactiveSource src, System.Random random, Texture iconAtlas) { source = src; atlas = iconAtlas; windowID = random.Next(); // Set up screen position screenPosition = Camera.main.WorldToScreenPoint(source.part.transform.position); windowPosition = new Rect(screenPosition.x+50f, Screen.height-screenPosition.y+windowDims.y/2f, windowDims.x, windowDims.y); GetStyles(); if (source.IconID == 0) atlasIconRect = new Rect(0f,0.5f,0.5f,0.5f); if (source.IconID == 1) atlasIconRect = new Rect(0.5f,0.5f,0.5f,0.5f); if (source.IconID == 2) atlasIconRect = new Rect(0f,0.0f,0.5f,0.5f); if (source.IconID == 3) atlasIconRect = new Rect(0.5f,0.0f,0.5f,0.5f); }
public static Deposit Generate(Vector2 Pos, float radius, System.Random random, ResourceDefinition resource) { var initialQuantity = random.Range(resource.MinQuantity, resource.MaxQuantity); var vertices = new List<Point>(); int vertexCount = random.Next(resource.MinVertices, resource.MaxVertices); for (int i = 0; i < vertexCount; i++) { float randomRadius = random.Range(resource.RadiusVariance * radius, radius); float angle = 2.0f * (float)Math.PI * ((float)i / (float)vertexCount); float x = Pos.x + randomRadius * (float)Math.Cos(angle); float z = Pos.y - randomRadius * (float)Math.Sin(angle); vertices.Add(new Point(x, z)); } var Shape = new Polygon(vertices.ToArray()); return new Deposit(Shape, initialQuantity, initialQuantity); }
void RandomHoles(int percent, System.Random r) { List<Cell> UsedCells = new List<Cell>(); for(int x = 1; x < MazeCells.GetLength(0)-1; x++) { for(int y = 1; y<MazeCells.GetLength(1)-1; y++) { if( MazeCells[x,y].isWall && !UsedCells.Contains(MazeCells[x,y])) { List<Cell> nB = MazeCells[x,y].Neighbors; int adj = 0; Cell n1 = null; Cell n2 = null; foreach(var v in nB) { if(v.isWall) { adj++; if(adj == 1) n1 = v; else if(adj == 2) n2 = v; } } if(adj == 2 && ((n1.x == n2.x) || (n1.y == n2.y))) { int rN = r.Next(0,100); if(rN > percent) { UsedCells.Add(n1); UsedCells.Add(n2); //Debug.Log("Want to Remove ("+x+","+y+")\nNeighbors: ("+nB[0].x+","+nB[0].y+") - ("+nB[1].x+","+nB[1].y+")"); MazeCells[x,y].isWall = false; } } } } } }
void SetTileSprite (int x, int y, GameObject tile_go, System.Random rnd) { //Tile Biome will be the intercator for what tile set to use e.g dirt or stone etc. Sprites will be prefixed "{Biome}_" //Ideally want to impliment a weighted spread where there's alterative versions for the sape sprite in the same set. EmptyTile t = world[x, y]; string s = t.Biome + "_"; SpriteRenderer tile_sr = tile_go.GetComponent<SpriteRenderer>(); if (t is Tiles.Floor) { int[] f = new int[] { 1, 1, 1, 1, 1, 3, 3, 3, 4, 4 }; s += "Floor_" + f[rnd.Next(0, 9)]; SpriteControler.SetTileSpriteRender(x, y, tile_sr, s); } else { tile_sr.sprite = empty; } }
public virtual string GetRandomName(ref System.Random rand) { var a = (char)(65 + rand.Next(0, 26)); var b = (char)(65 + rand.Next(0, 26)); var c = (char)(65 + rand.Next(0, 26)); var ch = new[]{a,b,c}; var s = new string(ch); var d = rand.Next(0, 10); var e = rand.Next(0, 10); var f = rand.Next(0, 10); s += d.ToString(); s += e.ToString(); s += f.ToString(); return s; }
private void RunReadBytes(IndexInput input, int bufferSize, System.Random r) { int pos = 0; // gradually increasing size: for (int size = 1; size < bufferSize * 10; size = size + size / 200 + 1) { CheckReadBytes(input, size, pos); pos += size; if (pos >= TEST_FILE_LENGTH) { // wrap pos = 0; input.Seek(0L); } } // wildly fluctuating size: for (long i = 0; i < 1000; i++) { int size = r.Next(10000); CheckReadBytes(input, 1 + size, pos); pos += 1 + size; if (pos >= TEST_FILE_LENGTH) { // wrap pos = 0; input.Seek(0L); } } // constant small size (7 bytes): for (int i = 0; i < bufferSize; i++) { CheckReadBytes(input, 7, pos); pos += 7; if (pos >= TEST_FILE_LENGTH) { // wrap pos = 0; input.Seek(0L); } } }
static IEnumerable<int> NextInt32SequenceEnumerable(System.Random rnd, int minInclusive, int maxExclusive) { while (true) { yield return rnd.Next(minInclusive, maxExclusive); } }
public void Shuffle(int times, System.Random random) { for (int time = 0; time < times; time++) { for (int i = 0; i < cards.Count; i++) { var card = cards[i]; var newIndex = random.Next(0, cards.Count); cards.Remove(card); cards.Insert(newIndex, card); } } }
// Random rnd is passed in so that the exact same random query may be created // more than once. public static BooleanQuery RandBoolQuery(System.Random rnd, int level, System.String field, System.String[] vals, TestBoolean2.Callback cb) { BooleanQuery current = new BooleanQuery(rnd.Next() < 0); for (int i = 0; i < rnd.Next(vals.Length) + 1; i++) { int qType = 0; // term query if (level > 0) { qType = rnd.Next(10); } Query q; if (qType < 7) q = new TermQuery(new Term(field, vals[rnd.Next(vals.Length)])); else q = RandBoolQuery(rnd, level - 1, field, vals, cb); int r = rnd.Next(10); BooleanClause.Occur occur; if (r < 2) occur = BooleanClause.Occur.MUST_NOT; else if (r < 5) occur = BooleanClause.Occur.MUST; else occur = BooleanClause.Occur.SHOULD; current.Add(q, occur); } if (cb != null) cb.PostCreate(current); return current; }
public UIRosterWindow(System.Random randomizer) { random = randomizer; windowIdentifier = randomizer.Next(); GetStyles(); }
/// <summary> /// Generates one sample from the discrete uniform distribution. This method does not do any parameter checking. /// </summary> /// <param name="rnd">The random source to use.</param> /// <param name="lower">Lower bound, inclusive. Range: lower ≤ upper.</param> /// <param name="upper">Upper bound, inclusive. Range: lower ≤ upper.</param> /// <returns>A random sample from the discrete uniform distribution.</returns> static int SampleUnchecked(System.Random rnd, int lower, int upper) { return rnd.Next(lower, upper + 1); }
//Creates terrain of various types void CreateTerrain(System.Random rand, TerrainGenType type) { tiles.Clear(); for(int ii = 0; ii < width*height; ii++){ tiles.Add(new Tile(TileState.PASSABLE,0, 100)); } switch(type){ case TerrainGenType.DIAMOND_SQUARE: CreateDiamondSquareTerrain (rand); break; case TerrainGenType.RANDOM: for(int ii = 0; ii < width*height; ii++){ if(0==rand.Next()%2){ Tile fuckingCSharp = tiles[ii]; fuckingCSharp.state = TileState.IMPASSABLE; tiles[ii] = fuckingCSharp; } } break; } }
/// <summary> /// Generates one sample from the discrete uniform distribution. This method does not do any parameter checking. /// </summary> /// <param name="rnd">The random source to use.</param> /// <param name="lower">The lower bound of the uniform random variable.</param> /// <param name="upper">The upper bound of the uniform random variable.</param> /// <returns>A random sample from the discrete uniform distribution.</returns> private static int DoSample(System.Random rnd, int lower, int upper) { return rnd.Next() % (upper - lower + 1) + lower; }
/// <summary> /// Retourne un chunk aleatoire. (Une copie) /// </summary> public static Chunk RandChunk(Bridges bridge, System.Random rand) { List<Chunk> chunks = new List<Chunk>(); foreach (Chunk c in Chunks) if (c.Bridge == bridge) chunks.Add(c); return new Chunk(chunks[rand.Next(chunks.Count)]); }
public static Sprite generateInvaderSprite(int width, int height, System.Random rng) { // Create data array int[] data = new int[width*height]; // Initialize sprite data with empty values for(int i=0; i<data.Length; i++) { data[i] = EMPTY; } // Create random invader for(int y=0; y<height; y++) { for(int x=0; x<width; x++) { // Even sized width if(width%2==0) { if(x < width/2) { data[y*height + x] = Mathf.RoundToInt((float)rng.NextDouble()); } else { data[y*height +x] = data[y*height + (width - x - 1)]; } } // Odd sized width else { if(x <= width/2) { data[y*height + x] = Mathf.RoundToInt((float)rng.NextDouble()); } else { data[y*height +x] = data[y*height + (width - x - 1)]; } } } } //Create the sprite's texture Texture2D texture = new Texture2D(width, height); // Set filter mode to point (removes blur) texture.filterMode = FilterMode.Point; // Apply colors // Only bright-ish colors (we have a dark background) float r = (float)rng.Next(100,256)/255; float g = (float)rng.Next(100,256)/255; float b = (float)rng.Next(100,256)/255; Color c = new Color(r, g, b); Color transparent = new Color(0,0,0,0); for(int x=0; x<width; x++) { for(int y=0; y<height; y++) { if(data[y*height +x] == FILLED) { texture.SetPixel(x, y, c); } else { texture.SetPixel(x,y,transparent); } } } //Apply changes to texture texture.Apply(); // Return sprite Sprite sprite = Sprite.Create(texture, new Rect(0,0,texture.width, texture.height), new Vector2(0.5f,0.5f), 100); return sprite; }
private Card PickRandomCard(System.Random random) { Array ranks = Enum.GetValues(typeof(Rank)); Array suits = Enum.GetValues(typeof(Suit)); Rank rank = (Rank)ranks.GetValue(random.Next(ranks.Length)); Suit suit = (Suit)suits.GetValue(random.Next(suits.Length)); return new Card(rank, suit); }