//Determine which primary system is being used //Outdated or Additive //New system replaces orange with cyan and purple with magenta //Primaries will return both primary and secondary colors. public static List <int> Primaries() { var i = _rng.Next(0, 2); var list1 = new List <int> { 0, 2, 4 }; var list2 = new List <int> { 0, 3, 4 }; var list3 = new List <int> { 1, 3, 5 }; var list4 = new List <int> { 1, 2, 5 }; if (i == 1) { Backgrounds.color[1] = UnityEngine.Color.cyan; Backgrounds.colorList[1] = "cyan"; Backgrounds.color[5] = UnityEngine.Color.magenta; Backgrounds.colorList[5] = "magenta"; return(list2.Concat(list4).ToList()); } return(list1.Concat(list3).ToList()); }
void Start() { rnd = RuleSeed.GetRNG(); var ixs = Enumerable.Range(0, allConditions.Count).ToList(); rnd.ShuffleFisherYates(ixs); for (int i = 0; i < 4; i++) { leftSwitch.Add(new Switch { Explanation = allConditions[ixs.First()].Explanation, Cond = allConditions[ixs.First()].Cond, SwitchValue = rnd.Next(1, 5) }); ixs.RemoveAt(0); rightSwitch.Add(new Switch { Explanation = allConditions[ixs.First()].Explanation, Cond = allConditions[ixs.First()].Cond, SwitchValue = rnd.Next(1, 5) }); ixs.RemoveAt(0); } leftSwitch.Add(new Switch { Explanation = "Otherwise", Cond = button => true, SwitchValue = rnd.Next(1, 5) }); rightSwitch.Add(new Switch { Explanation = "Otherwise", Cond = button => true, SwitchValue = rnd.Next(1, 5) }); MixButtons(); StartCoroutine(Game()); }
public static Instruction[,] GetRules(int ruleSeed) { var random = new MonoRandom(ruleSeed); var weights = new WeightMap <Instruction, string>(i => i.Key); var rules = new Instruction[NumStages, 4]; for (int i = 0; i < NumStages; ++i) { for (int j = 0; j < 4; ++j) { var digit = random.Next(1, 5); var stage = random.Next(1, i + 1); var instructions = new List <Instruction>() { Instruction.Position1, Instruction.Position2, Instruction.Position3, Instruction.Position4, Instruction.PressDigit(digit) }; if (i > 0) { var instruction = i % 2 == 0 ? Instruction.PressLabelFromStage(stage) : Instruction.PressPositionFromStage(stage); if (i > 2) { weights.SetWeight(instruction, 1); } instructions.Add(instruction); } var instruction2 = weights.Roll(instructions, random); rules[i, j] = instruction2; } } return(rules); }
public void PopulateMaze(MonoRandom rng) { var cellStack = new Stack <MazeCell>(); var x = rng.Next(0, Size); var y = rng.Next(0, Size); var cell = GetCell(x, y); VisitCell(cell, cellStack, rng); }
// Use this for initialization public void Start() { this.moduleId = moduleIdCounter++; this.DisplayTextMesh.text = ""; // clear display this.LCDCoverUpMaterialCopy = new Material(this.LCDCoverUpMaterial); this.LCDRenderMesh.material = this.LCDCoverUpMaterialCopy; // set button positions for (int i = 1; i < 10; i++) { var btn1Pos = this.NumberButtons[0].transform.localPosition; this.NumberButtons[i].transform.localPosition = new Vector3(btn1Pos.x + 0.0245f * (i % 5), btn1Pos.y, btn1Pos.z - 0.028f * (i / 5)); this.NumberButtons[i].transform.localScale = this.NumberButtons[0].transform.localScale; } GetComponent <KMBombModule>().OnActivate += ModuleActivated; // pick characters var len = characterList.Count; var chosenLetterKVs = new List <KeyValuePair <ushort, string> >(letterCount); for (int i = 0; i < letterCount; i++) { chosenLetterKVs.Add(characterList.ElementAt(rand.Next(len))); } this.chosenLetters = chosenLetterKVs.Select(x => x.Value).ToArray(); this.expectedCode = chosenLetterKVs.SelectMany(x => GetDigits(x.Key)).ToArray(); this.enteredCode = new List <byte>(this.expectedCode.Length); Log("Letter generation finished. Expected code: " + string.Join(null, this.expectedCode.Select(x => x.ToString()).ToArray())); Log("Grouped code: " + string.Join(" ", chosenLetterKVs.Select(x => x.Key.ToString()).ToArray())); }
private static int[] GenerateTableOfNumbers(MonoRandom rnd) { // Generate the 12×12 grid of numbers 1–5 (still part of rule seed) var _table = new int[144]; var nmbrs = new List <int>(); for (var i = 0; i < 144; i++) { nmbrs.Clear(); var x = i % 12; var y = (i / 12) | 0; for (var j = 0; j < 5; j++) { if ((x == 0 || j != _table[i - 1]) && (y == 0 || j != _table[i - 12]) && (x == 0 || y == 0 || j != _table[i - 13])) { nmbrs.Add(j); } } var n = nmbrs[rnd.Next(0, nmbrs.Count)]; _table[i] = n; } return(_table); }
private static Rule[][] GenerateRules(MonoRandom rnd, ref FACScript FAC) { FAC.Audio.PlaySoundAtTransform("start", FAC.Module.transform); if (rnd.Seed == 1) { return(new Rule[0][]); } var rules = new Rule[2][] { new Rule[24], new Rule[8] }; int[] ranges = { 10, 30 }; for (int i = 0; i < rules.Length; i++) { for (int j = 0; j < rules[i].Length; j++) { rules[i][j] = new Rule { Number = rnd.Next(ranges[i]) }; } } return(rules); }
HashSet <int> VisitConfigurations(int startConfiguration, MonoRandom rnd) { var visitedConfigurations = new HashSet <int>(); var visitStack = new Stack <int>(); visitStack.Push(startConfiguration); while (true) { if (visitedConfigurations.Count >= (1 << _numSwitches) - _numForbiddenConfigurations) { return(visitedConfigurations); } int configToVisit = visitStack.Pop(); if (!visitedConfigurations.Add(configToVisit)) { continue; } var adjacentConfigurations = GetAdjacentConfigurations(configToVisit).ToList(); while (adjacentConfigurations.Count > 0) { var ix = rnd.Next(0, adjacentConfigurations.Count); visitStack.Push(adjacentConfigurations[ix]); adjacentConfigurations.RemoveAt(ix); } } }
public static List <string> GetSimilarWords(List <string> chosenWords, List <string> words, int totalWordsRequired, MonoRandom rng, bool log = true) { var numBaseWords = chosenWords.Count; for (var i = 0; i < numBaseWords && chosenWords.Count < 36; i++) { var prefix = chosenWords[i].Substring(1); var toAdd = words .Where(w => !chosenWords.Contains(w) && !w.EndsWith(prefix)) .Select(w => (new { word = w, pref = rng.NextDouble(), dist = Similarity(w, chosenWords[i]) })) .ToList(); toAdd.Sort((a, b) => { var r = a.dist - b.dist; return(r == 0 ? Math.Sign(a.pref - b.pref) : r); }); var howmany = Math.Min(Math.Min(rng.Next(1, 4), 36 - chosenWords.Count), toAdd.Count); if (log) { Debug.LogFormat(@"[Password rule seed] From {0}, adding words: {1}", chosenWords[i], string.Join(", ", toAdd.Take(howmany).Select(w => string.Format("{0}/{1}/{2}", w.word, w.dist, w.pref)).ToArray())); } chosenWords.AddRange(toAdd.Take(howmany).Select(inf => inf.word)); } return(chosenWords); }
public static Glyph[][] GetColumns(int ruleSeed) { var random = new MonoRandom(ruleSeed); var unusedGlyphs = new List <Glyph>() { Copyright, FilledStar, HollowStar, SmileyFace, DoubleK, Omega, SquidKnife, Pumpkin, HookN, Teepee, Six, SquigglyN, AT, Ae, MeltedThree, Euro, Circle, NWithHat, Dragon, QuestionMark, Paragraph, RightC, LeftC, Pitchfork, Tripod, Cursive, Tracks, Balloon, WeirdNose, UpsideDownY, BT }; var columns = new Glyph[6][]; var singleGlyphs = new List <Glyph>(); for (var i = 0; i < 6; i++) { var column = new Glyph[7]; columns[i] = column; var j = 0; // Repeat up to 3 glyphs from previous columns. // (No glyph will appear in more than two columns.) if (i > 0) { while (j < 3) { if (singleGlyphs.Count == 0) { break; } var glyph = Utils.RemoveRandom(singleGlyphs, random); column[j] = glyph; j++; } } // Add unused glyphs. (These may be repeated later.) while (j < 7) { var glyph = Utils.RemoveRandom(unusedGlyphs, random); column[j] = glyph; singleGlyphs.Add(glyph); j++; } // Shuffle the column. for (j = 0; j < column.Length; j++) { var hold = column[j]; var index = random.Next(column.Length); column[j] = column[index]; column[index] = hold; } } return(columns); }
public static Colour[,,] GetRules(int ruleSeed) { if (ruleSeed == 1) { return new[, , ] { // If the serial number does not contain a vowel { { Blue, Yellow, Green, Red }, { Red, Blue, Yellow, Green }, { Yellow, Green, Blue, Red } }, // If the serial number contains a vowel { { Blue, Red, Yellow, Green }, { Yellow, Green, Blue, Red }, { Green, Red, Yellow, Blue } } } } ; var random = new MonoRandom(ruleSeed); var colours = new Colour[2, 3, 4]; for (int i = 1; i >= 0; --i) { for (int j = 0; j < 3; ++j) { for (int k = 0; k < 4; ++k) { colours[i, j, k] = (Colour)random.Next(4); } // Make sure they're not all the same. while (colours[i, j, 1] == colours[i, j, 0] && colours[i, j, 2] == colours[i, j, 0] && colours[i, j, 3] == colours[i, j, 0]) { colours[i, j, random.Next(4)] = (Colour)random.Next(4); } } } return(colours); }
private void Start() { rnd = RuleSeedable.GetRNG(); int seed = rnd.Seed; if (seed == 1) { YesAns = YesButton; NoAns = NoButton; UsesVanillaRuleModifierAPI = false; } else { int yes = rnd.Next(0, 2); int no = rnd.Next(0, 2); switch (yes) { case 0: YesAns = NoButton; break; default: YesAns = YesButton; break; } switch (no) { case 0: NoAns = YesButton; break; default: NoAns = NoButton; break; } UsesVanillaRuleModifierAPI = true; } _moduleId = _moduleIdCounter++; Module.OnActivate += Activate; }
bool[] FindGrid(bool[] grid, int ix, List <bool[]> gridsAlready, MonoRandom rnd) { if (ix % 5 == 0) { for (var prevRow = 0; prevRow * 5 < ix - 5; prevRow++) { if (Enumerable.Range(0, 5).All(x => grid[prevRow * 5 + x] == grid[ix - 5 + x])) { return(null); } } } if (ix == 25) { for (var col = 0; col < 5; col++) { for (var col2 = 0; col2 < col; col2++) { if (Enumerable.Range(0, 5).All(y => grid[y * 5 + col] == grid[y * 5 + col2])) { return(null); } } } if (gridsAlready.All(gr => { for (var j = 0; j < 25; j++) { if (gr[j] != grid[j]) { return(true); } } return(false); })) { return(grid); } return(null); } var pixel = rnd.Next(0, 2) != 0; grid[ix] = pixel; var success = FindGrid(grid, ix + 1, gridsAlready, rnd); if (success != null) { return(success); } grid[ix] = !pixel; return(FindGrid(grid, ix + 1, gridsAlready, rnd)); }
public void BuildMaze(MonoRandom rng) { for (var i = 0; i < Size; i++) { for (var j = 0; j < Size; j++) { if (i > 0) { rng.Next(); } if (j > 0) { rng.Next(); } } } PopulateMaze(rng); rng.Next(); rng.Next(); //Burn the coordinate circles. }
private void GenerateRules() { MonoRandom rnd = RuleSeedable.GetRNG(); Debug.LogFormat(@"[VaricoloredSquares #{0}] Rule Generator: generating rules according to rule seed {1}", _moduleId, rnd.Seed); // Add more random spread for (int i = 0; i < 13; i++) { rnd.Next(); } // Generate color pentagons _table = new SquareColor[5][]; for (int i = 0; i < 5; i++) { _colorCandidates.Shuffle(rnd); _table[i] = _colorCandidates.ToArray(); Debug.LogFormat(@"[VaricoloredSquares #{0}] Rule Generator: {1} pentagon is: {2}", _moduleId, (SquareColor)i, string.Join("-", _table[i].Select(c => "RBGYM"[(int)c].ToString()).ToArray())); } // Random spread rnd.Next(); rnd.Next(); rnd.Next(); // Generate directions _ruleOneDirection = (rnd.Next(2) * 2) - 1; _backupDirection = (rnd.Next(2) * 2) - 1; Debug.LogFormat(@"[VaricoloredSquares #{0}] Rule Generator: rule one direction is: {1}", _moduleId, _ruleOneDirection == -1 ? "counter-clockwise" : "clockwise"); Debug.LogFormat(@"[VaricoloredSquares #{0}] Rule Generator: backup rule direction is: {1}", _moduleId, _backupDirection == -1 ? "counter-clockwise" : "clockwise"); }
int ChooseUniqueRND(int maxVal) { var nowVal = 0; do { nowVal = rnd.Next(maxVal); } while (pickedValues.Contains(nowVal)); pickedValues.Add(nowVal); return(nowVal); }
public static void Shuffle <T>(this IList <T> list, MonoRandom random) { int n = list.Count; while (n > 1) { n--; int k = random.Next(0, n + 1); T value = list[k]; list[k] = list[n]; list[n] = value; } }
IEnumerable <int> GetForbiddenConfigurations(MonoRandom rnd) { var startPoint = rnd.Next(0, 1 << _numSwitches); var visitedConfigurations = VisitConfigurations(startPoint, rnd); for (var i = 0; i < (1 << _numSwitches); i++) { if (!visitedConfigurations.Contains(i)) { yield return(i); } } }
void HandleRuleSeed() { string[] currentQuotes = allPossibleQuotes.ToArray(); if (ruleSeedCore != null) { var randomizer = ruleSeedCore.GetRNG(); randomizer.ShuffleFisherYates(currentQuotes); RSReversePriorityLabeled = randomizer.Next(0, 2) != 1; RSReversePriorityUnlabeled = randomizer.Next(0, 2) != 1; QuickLog(string.Format("Ruleseed successfully generated with a seed of {0}.", randomizer.Seed)); if (randomizer.Seed == 1) { relabeledStageOrder = new[] { 0, 1, 2, 3, -1 } } ; else { relabeledStageOrder = new[] { 0, 2, 3, 4, -1 }; } } else { QuickLog("Ruleseed handler does not exist. Using default instructions."); var randomizer = new MonoRandom(1); randomizer.ShuffleFisherYates(currentQuotes); RSReversePriorityLabeled = randomizer.Next(0, 2) != 1; RSReversePriorityUnlabeled = randomizer.Next(0, 2) != 1; relabeledStageOrder = new[] { 0, 1, 2, 3, -1 }; } shuffledQuotes = currentQuotes.ToArray(); Debug.LogFormat("<Labeled Priorities Plus #{0}> All phrases from top to bottom:", modID); for (int x = 0; x < shuffledQuotes.Length; x++) { Debug.LogFormat("<Labeled Priorities Plus #{0}> {2}: \"{1}\"", modID, shuffledQuotes[x].Replace("\n", " "), x + 1); } Debug.LogFormat("<Labeled Priorities Plus #{0}> Phrase priority when disarming Labeled Priorities: {1}", modID, RSReversePriorityLabeled ? "low to high" : "high to low"); Debug.LogFormat("<Labeled Priorities Plus #{0}> Phrase priority when disarming Unlabeled Priorities: {1}", modID, RSReversePriorityUnlabeled ? "low to high" : "high to low"); }
// Fisher-Yates Shuffle public static IList <T> Shuffle <T>(this IList <T> list, MonoRandom rnd) { int i = list.Count; while (i > 1) { int index = rnd.Next(i); i--; T value = list[index]; list[index] = list[i]; list[i] = value; } return(list); }
private string GenerateFileName(int minLength, int maxLength) { int length = monoRandom.Next(minLength, maxLength); int pivot = length / 2; string name = ""; // Generates first half. int w = monoRandom.Next(0, moduleEntryCount) * moduleLength; string word = modulePrefixText.Substring(w, moduleLength); for (int j = 0; j < pivot; j++) { if (j >= word.Length || word[j] == ' ') { break; } else { name += word[j]; } } // Generates second half. w = monoRandom.Next(0, moduleEntryCount) * moduleLength; word = moduleSuffixtext.Substring(w, moduleLength); for (int j = word.Length - pivot; j < word.Length; j++) { if (j < 0 || word[j] == ' ') { continue; } else { name += word[j]; } } // generates extention w = monoRandom.Next(0, extentionEntryCount) * extentionLength; word = extentionText.Substring(w, extentionLength); word = word.Trim(); name += "." + word; return(name); }
void Setup() { stage = -1; center = Random.Range(1, 10); if (!alreadyInitialized) { rnd.ShuffleFisherYates(gridDigits); } var counter = 0; for (int i = 0; i < grid.Length; i++) { for (int j = 0; j < grid[i].Length; j++) { grid[i][j] = gridDigits[counter]; if (gridDigits[counter] == center) { y = i; x = j; } counter++; } } if (!alreadyInitialized) { for (int i = 0; i < lookUp.Length; i++) { for (int j = 0; j < lookUp[i].Length; j++) { lookUp[i][j] = rnd.Next(1, 5); } } } alreadyInitialized = true; Debug.LogFormat(@"[Navinums #{0}] Center Display is: {1}.", moduleId, center); Debug.LogFormat(@"[Navinums #{0}] Using the following grid:", moduleId); for (int i = 0; i < grid.Length; i++) { Debug.LogFormat(@"[Navinums #{0}] {1}", moduleId, grid[i].Join(", ")); } Debug.LogFormat(@"[Navinums #{0}] Using the following lookups:", moduleId); for (int i = 0; i < lookUp.Length; i++) { Debug.LogFormat(@"[Navinums #{0}] {1}: {2}", moduleId, i + 1, lookUp[i].Join(", ")); } GenerateStage(); }
public static void GenerateRules(MonoRandom rng) { if (_rng != null && _rng.Seed == rng.Seed) { return; } _rng = rng; Mazes.Clear(); for (var i = 0; i < 18; i++) { var maze = new Maze(); Mazes.Add(maze); maze.BuildMaze(rng); } var words = new List <string>(PossibleWords); words.AddRange(ExtendedWords); // Choose 8 base words var numBaseWords = 18; var chosenWords = words.OrderBy(x => rng.NextDouble()).Take(numBaseWords).ToList(); Debug.LogFormat("[Morse Code Rule Seed Generator] + Base words: {0}", string.Join(", ", chosenWords.ToArray())); // Find other words that are similar to these (low cycling Levenshtein distance) for (var i = 0; i < numBaseWords && chosenWords.Count < 36; i++) { var prefix = chosenWords[i].Substring(1); var toAdd = words .Where(w => !chosenWords.Contains(w) && !w.EndsWith(prefix)) .Select(w => (new { word = w, pref = rng.NextDouble(), dist = Similarity(w, chosenWords[i]) })) .ToList(); toAdd.Sort((a, b) => { var r = a.dist - b.dist; return(r == 0 ? Math.Sign(a.pref - b.pref) : r); }); var howmany = Math.Min(Math.Min(rng.Next(1, 4), 36 - chosenWords.Count), toAdd.Count); Debug.LogFormat(@"[Password rule seed] From {0}, adding words: {1}", chosenWords[i], string.Join(", ", toAdd.Take(howmany).Select(w => string.Format("{0}/{1}/{2}", w.word, w.dist, w.pref)).ToArray())); chosenWords.AddRange(toAdd.Take(howmany).Select(inf => inf.word)); } Words.Clear(); Words.AddRange(chosenWords.Take(36).OrderBy(x => rng.NextDouble())); }
public static T Shuffle <T>(this T list, MonoRandom rnd) where T : IList { if (list == null) { throw new ArgumentNullException("list"); } for (int j = list.Count; j >= 1; j--) { int item = rnd.Next(0, j); if (item < j - 1) { var t = list[item]; list[item] = list[j - 1]; list[j - 1] = t; } } return(list); }
private void initDicts(MonoRandom rng) { if (rng.Seed == 1) { addSymbol('ใ', new int[] { 5, 0, 4 }, new char[] { 'G', 'D', 'G' }); addSymbol('ɮ', new int[] { 4, 0, 5 }, new char[] { 'Z', 'D', 'R' }); addSymbol('ʖ', new int[] { 0, -1, 4 }, new char[] { 'C', 'S', 'O' }); addSymbol('ฬ', new int[] { 0, 2, 5 }, new char[] { 'J', 'X', 'Y' }); addSymbol('น', new int[] { 2, 1, 2 }, new char[] { 'V', 'B', 'L' }); addSymbol('Þ', new int[] { -2, 5, 5 }, new char[] { 'T', 'L', 'J' }); addSymbol('ฏ', new int[] { 4, 1, 2 }, new char[] { 'L', 'A', 'O' }); addSymbol('Ѩ', new int[] { 3, 5, 4 }, new char[] { 'G', 'A', 'S' }); addSymbol('Ԉ', new int[] { 4, 4, 2 }, new char[] { 'F', 'S', 'M' }); addSymbol('Ԓ', new int[] { 3, 2, 3 }, new char[] { 'P', 'O', 'F' }); addSymbol('ด', new int[] { -1, 3, 4 }, new char[] { 'K', 'Q', 'K' }); addSymbol('ล', new int[] { -1, -2, 4 }, new char[] { 'D', 'N', 'L' }); addSymbol('Ж', new int[] { 5, 0, 5 }, new char[] { 'Q', 'O', 'Z' }); //addSymbol('Ⴟ', new int[] { 5, 5, 3 }, new char[] { 'W', 'M', 'C' }); } else { for (var index = 0; index < rng.Next(0, 25); index++) { rng.NextDouble(); } var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; foreach (var c in "ใɮʖฬนÞฏѨԈԒดลЖႿ".OrderBy(x => rng.NextDouble()).Take(13)) { var x = rng.Next(0, 8) - 2; var y = rng.Next(0, 8) - 2; var z = rng.Next(2, 6); var i = alphabet[rng.Next(0, 26)]; var j = alphabet[rng.Next(0, 26)]; var k = alphabet[rng.Next(0, 26)]; addSymbol(c, new int[] { x, y, z }, new char[] { i, j, k }); } labels = labels.OrderBy(x => rng.NextDouble()).ToArray(); } chars = new List <char>(answers.Keys); }
private static string[] GetWordsInternal(int ruleSeed) { if (ruleSeed == 1) { return((string[])vanillaPasswords.Clone()); } var random = new MonoRandom(ruleSeed); // Start with 17 random words from the list. var words1 = new string[passwords.Length]; Array.Copy(passwords, words1, passwords.Length); words1 = random.Shuffle(words1); var words = new string[35]; Array.Copy(words1, words, 17); // Add more words that are similar to the base words. int count = 17; for (var i = 0; i < 17 && count < 35; i++) { var toAdd = (from w in passwords where !words.Contains(w) select(word: w, pref: random.NextDouble(), dist: HammingDistance(w, words[i]))).ToArray(); Array.Sort(toAdd, (a, b) => { var r = a.dist - b.dist; return(r == 0 ? a.pref.CompareTo(b.pref) : r); }); var numberToAdd = Math.Min(random.Next(1, 5), 35 - count); for (int j = 0; j < numberToAdd; ++j) { words[count] = toAdd[j].word; ++count; } } Array.Sort(words); return(words); }
public static RuleSet GetRules(int ruleSeed) { var random = new MonoRandom(ruleSeed); var displayRules = new Dictionary <string, int>(StringComparer.CurrentCultureIgnoreCase); var buttonRules = new Dictionary <string, string[]>(StringComparer.CurrentCultureIgnoreCase); foreach (var word in displayTexts) { displayRules[word] = random.Next(6); } for (int i = 0; i < buttonTexts.Length; ++i) { for (int j = 0; j < buttonTexts[i].Length; ++j) { var array = (string[])buttonTexts[i].Clone(); random.ShuffleFisherYates(array); buttonRules[buttonTexts[i][j]] = array; } } return(new RuleSet(displayRules, buttonRules)); }
public MazeCell GetNextNeigbour(MazeCell cell, MonoRandom rng) { var list = new List <MazeCell>(); if (cell.X > 0 && !CellGrid[cell.X - 1][cell.Y].Visited) { list.Add(CellGrid[cell.X - 1][cell.Y]); } if (cell.X < CellGrid.Count - 1 && !CellGrid[cell.X + 1][cell.Y].Visited) { list.Add(CellGrid[cell.X + 1][cell.Y]); } if (cell.Y > 0 && !CellGrid[cell.X][cell.Y - 1].Visited) { list.Add(CellGrid[cell.X][cell.Y - 1]); } if (cell.Y < CellGrid[cell.X].Count - 1 && !CellGrid[cell.X][cell.Y + 1].Visited) { list.Add(CellGrid[cell.X][cell.Y + 1]); } return(list.Count > 0 ? list[rng.Next(0, list.Count)] : null); }
private List <Flag> generateFlags(int count, FlagDesign[] designs, MonoRandom rnd, string[] flagNames) { // Each design can be used different numbers of times var designIxsAvailable = new List <int>(); for (var i = 0; i < designs.Length; i++) { var allowed = designs.Length == 4 ? 1 : designs[i].NumColors == 4 ? 1 : designs[i].NumColors == 2 && designs[i].ReverseAllowed ? 4 : 3; for (var j = 0; j < allowed; j++) { designIxsAvailable.Add(i); } } // Assign designs at random var flags = new List <Flag>(); var colorCombinations = new Dictionary <int, List <int[]> >(); var availableColorIxs = Enumerable.Range(0, _colorGroups.Length).ToList(); for (var i = 0; i < count; i++) { var ix = rnd.Next(0, designIxsAvailable.Count); var designIx = designIxsAvailable[ix]; designIxsAvailable.RemoveAt(ix); ColorInfo[] flagColors; if (designs[designIx].NumColors == 4) { // 4-color designs are allowed to have blue+black and/or yellow+white, but only in a specific order. flagColors = new ColorInfo[4]; var fcIx = 0; rnd.ShuffleFisherYates(availableColorIxs); var ixIx = 0; while (fcIx < 4) { for (var j = 0; j < _colorGroups[availableColorIxs[ixIx]].Length && fcIx < 4; j++) { flagColors[fcIx] = _colorGroups[availableColorIxs[ixIx]][j]; fcIx++; if (fcIx % 2 == 0) { break; } } ixIx++; } } else { // Find a random color combination that hasn’t been used yet. // Use only one color per group so we don’t get black+blue or yellow+white on the same flag. int[] colorIxs; do { rnd.ShuffleFisherYates(availableColorIxs); colorIxs = availableColorIxs.Take(designs[designIx].NumColors).ToArray(); }while (colorCombinations.ContainsKey(designIx) && colorCombinations[designIx].Any(cc => cc.SequenceEqual(colorIxs) || (!designs[designIx].ReverseAllowed && cc.Reverse().SequenceEqual(colorIxs)))); if (!colorCombinations.ContainsKey(designIx)) { colorCombinations[designIx] = new List <int[]>(); } colorCombinations[designIx].Add(colorIxs); do { flagColors = colorIxs.Select(cix => _colorGroups[cix][rnd.Next(0, _colorGroups[cix].Length)]).ToArray(); } // Special case: don’t allow entirely black-and-white flags while (designs[designIx].NumColors == 2 && ((flagColors[0].Name == "black" && flagColors[1].Name == "white") || (flagColors[0].Name == "white" && flagColors[1].Name == "black"))); } var cutout = designs[designIx].CutoutAllowed && (rnd.Next(0, 10) == 0); DebugLog("Flag {0} is {1}{2}", flagNames[i], string.Format(designs[designIx].NameFmt, flagColors.Select(cc => (object)cc.Name).ToArray()), cutout ? " with cutout" : ""); flags.Add(new Flag(designs[designIx], flagColors, cutout: cutout)); } return(flags); }
public static Rule[][] GetRules(int ruleSeed) { if (ruleSeed == 1) { return(new[] { // 3 wires new[] { new Rule(new[] { NoColourWire.GetCondition(Colour.Red) }, new Instruction(CutWire1)), new Rule(new[] { LastWireIsColour.GetCondition(Colour.White) }, new Instruction(CutWireLast)), new Rule(new[] { MoreThanOneColourWire.GetCondition(Colour.Blue) }, new Instruction(CutWireColourLast, Colour.Blue)), new Rule(new Instruction(CutWireLast)) }, // 4 wires new[] { new Rule(new[] { MoreThanOneColourWire.GetCondition(Colour.Red), Condition <Colour[]> .SerialNumberIsOdd() }, new Instruction(CutWireColourLast, Colour.Red)), new Rule(new[] { LastWireIsColour.GetCondition(Colour.Yellow), NoColourWire.GetCondition(Colour.Red) }, new Instruction(CutWire0)), new Rule(new[] { ExactlyOneColourWire.GetCondition(Colour.Blue) }, new Instruction(CutWire0)), new Rule(new[] { MoreThanOneColourWire.GetCondition(Colour.Yellow) }, new Instruction(CutWireLast)), new Rule(new Instruction(CutWire1)) }, // 5 wires new[] { new Rule(new[] { LastWireIsColour.GetCondition(Colour.Black), Condition <Colour[]> .SerialNumberIsOdd() }, new Instruction(CutWire3)), new Rule(new[] { ExactlyOneColourWire.GetCondition(Colour.Red), MoreThanOneColourWire.GetCondition(Colour.Yellow) }, new Instruction(CutWire0)), new Rule(new[] { NoColourWire.GetCondition(Colour.Black) }, new Instruction(CutWire1)), new Rule(new Instruction(CutWire0)) }, // 6 wires new[] { new Rule(new[] { NoColourWire.GetCondition(Colour.Yellow), Condition <Colour[]> .SerialNumberIsOdd() }, new Instruction(CutWire2)), new Rule(new[] { ExactlyOneColourWire.GetCondition(Colour.Yellow), MoreThanOneColourWire.GetCondition(Colour.White) }, new Instruction(CutWire3)), new Rule(new[] { NoColourWire.GetCondition(Colour.Red) }, new Instruction(CutWireLast)), new Rule(new Instruction(CutWire3)) } }); } var random = new MonoRandom(ruleSeed); var ruleSets = new Rule[4][]; for (int i = 3; i <= 6; ++i) { ConditionType[][] list; var conditionWeights = new WeightMap <ConditionType, string>(c => c.Key); var instructionWeights = new WeightMap <InstructionType, string>(s => s.Key); var list2 = new List <Rule>(); if (ruleSeed == 1) { list = new[] { new[] { new ConditionType(Condition <Colour[]> .SerialNumberStartsWithLetter()), new ConditionType(Condition <Colour[]> .SerialNumberIsOdd()) }, new[] { ExactlyOneColourWire, NoColourWire, LastWireIsColour, MoreThanOneColourWire } } } ; else { list = new[] { new[] { new ConditionType(Condition <Colour[]> .SerialNumberStartsWithLetter()), new ConditionType(Condition <Colour[]> .SerialNumberIsOdd()) }, new[] { ExactlyOneColourWire, NoColourWire, LastWireIsColour, MoreThanOneColourWire }, new[] { new ConditionType(Condition <Colour[]> .PortExactKey(PortType.DviD)), new ConditionType(Condition <Colour[]> .PortExactKey(PortType.PS2)), new ConditionType(Condition <Colour[]> .PortExactKey(PortType.RJ45)), new ConditionType(Condition <Colour[]> .PortExactKey(PortType.StereoRCA)), new ConditionType(Condition <Colour[]> .PortExactKey(PortType.Parallel)), new ConditionType(Condition <Colour[]> .PortExactKey(PortType.Serial)), new ConditionType(Condition <Colour[]> .EmptyPortPlate()) } } }; var rules = new Rule[random.NextDouble() < 0.6 ? 3 : 4]; ruleSets[i - 3] = rules; for (int j = 0; j < rules.Length; ++j) { var colours = new List <Colour>(WiresSolver.colours); var list3 = new List <Colour>(); var conditions = new Condition <Colour[]> [random.NextDouble() < 0.6 ? 1: 2]; var num = i - 1; for (int k = 0; k < conditions.Length; ++k) { var possibleQueryableProperties = GetPossibleConditions(list, num, k > 0); #if TRACE if (System.Diagnostics.Debugger.IsAttached) { System.Diagnostics.Trace.WriteLine("queryWeights:"); foreach (var entry in conditionWeights) { System.Diagnostics.Trace.WriteLine($" -- {entry.Key} = {entry.Value}"); } } #endif var conditionType = conditionWeights.Roll(possibleQueryableProperties, random, 0.1f); if (conditionType.UsesColour) { num -= conditionType.WiresInvolved; var i4 = random.Next(0, colours.Count); var colour = colours[i4]; colours.RemoveAt(i4); if (conditionType.ColourAvailableForSolution) { list3.Add(colour); } conditions[k] = conditionType.GetCondition(colour); } else { conditions[k] = conditionType.GetCondition(0); } } var instructions = GetPossibleInstructions(i, conditions); Instruction solution; var instructionType = instructionWeights.Roll(instructions, random); if (list3.Count > 0) { solution = new Instruction(instructionType, list3[random.Next(0, list3.Count)]); } else { solution = new Instruction(instructionType); } var rule = new Rule(conditions, solution); if (ruleSeed == 1 || rule.IsValid) { list2.Add(rule); } else { --j; } } Utils.StableSort(list2, r => - r.Queries.Length); var list4 = GetPossibleInstructions(i, null); if (ruleSeed != 1) { // Remove redundant rules. var forbiddenId = list2[list2.Count - 1].Solution.Type.Key; list4.RemoveAll(l => l.Key == forbiddenId); } list2.Add(new Rule(new Instruction(random.Pick(list4), null))); ruleSets[i - 3] = list2.ToArray(); } return(ruleSets); }