public void add() { Assert.Throws<ArgumentNullException>(() => CollectionsExtensions.Add(null, Enumerable.Empty<object>())); Assert.Throws<ArgumentNullException>(() => new object[0].Add(null)); ICollection<string> first = new HashSet<string> {"first"}; ICollection<string> second = new List<string> {"second"}; first.Add(second); Assert.Equal(2, first.Count); Assert.Equal("first", first.ElementAt(0)); Assert.Equal("second", first.ElementAt(1)); }
static void Main() { bool found = false; int n = int.Parse(Console.ReadLine()); var numbers = new HashSet<int>(Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse)); int numOfSubsets = 1 << numbers.Count; for (int i = 0; i < numOfSubsets; i++) { List<int> subset = new List<int>(); int pos = numbers.Count - 1; int b = i; while (b > 0) { if ((b & 1) == 1) subset.Add(numbers.ElementAt<int>(pos)); b >>= 1; pos--; } if ((subset.Sum() == n) && (subset.Count != 0)) { found = true; Console.WriteLine(string.Join(" + ", subset) + " = {0}", n); } } if (!found) Console.WriteLine("No matching subsets."); }
public override Unit GetNextTarget(HashSet<Unit> units) { if (units.Count > 0) { return units.ElementAt(0); } return null; }
static List<HashSet<int>> GetAllSubsets(HashSet<int> s) { if (s.Count == 0) return null; s = new HashSet<int>(s);//Copy the set so the original one will not be modified. int element = s.ElementAt(0); s.Remove(element); List<HashSet<int>> list = GetAllSubsetsHelper(element, s); return list; }
public void AktualizatorBrzeżnościRogówOdpowiednioJePrzypisuje(int indeksInicjatora, BrzeznoscRogu spodziewanaBrzeznoscR1, BrzeznoscRogu spodziewanaBrzeznoscR2, BrzeznoscRogu spodziewanaBrzeznoscR3, BrzeznoscRogu spodziewanaBrzeznoscR4, BrzeznoscRogu spodziewanaBrzeznoscR5) { _komorki = MockKomorek(); _rogi = MockRogow(_komorki); IMapa mapa = MockKlasyMapa(_komorki, _rogi); IKomorka inicjator = _komorki.ElementAt(indeksInicjatora); var rozdzielacz = new RozdzielaczMorzIJezior(inicjator) { Nastepnik = new AktualizatorBrzeznosciRogow() }; mapa.ZastosujPrzetwarzanie(rozdzielacz); _rogi.ElementAt(0).Dane.Brzeznosc.ShouldEqual(spodziewanaBrzeznoscR1); _rogi.ElementAt(1).Dane.Brzeznosc.ShouldEqual(spodziewanaBrzeznoscR2); _rogi.ElementAt(2).Dane.Brzeznosc.ShouldEqual(spodziewanaBrzeznoscR3); _rogi.ElementAt(3).Dane.Brzeznosc.ShouldEqual(spodziewanaBrzeznoscR4); _rogi.ElementAt(4).Dane.Brzeznosc.ShouldEqual(spodziewanaBrzeznoscR5); }
static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); var numbers = new HashSet<int>(Array.ConvertAll(Console.ReadLine().Split(' '), int.Parse)); List<List<int>> unsorted = new List<List<int>>(); bool found = false; int numOfSubsets = 1 << numbers.Count; for (int i = 0; i < numOfSubsets; i++) { List<int> subset = new List<int>(); int pos = numbers.Count - 1; int bitmask = i; while (bitmask > 0) { if ((bitmask & 1) == 1) { subset.Add(numbers.ElementAt<int>(pos)); } bitmask >>= 1; pos--; } if ((subset.Sum() == n) && (subset.Count != 0)) { found = true; subset.Sort(); unsorted.Add(subset); } } List<List<int>> results = unsorted.OrderBy(x => x.Count).ThenBy(x => x.ElementAt(0)).ToList(); if (found) { foreach (List<int> list in results) { Console.WriteLine(string.Join(" + ", list) + " = " + n); } } else { Console.WriteLine("No matching subsets."); } }
private void buttonOk_Click(object sender, EventArgs e) { if (listBox1.SelectedItem != null) { SelectedTable = (ITable)listBox1.SelectedItem; HashSet<ITable> tables = new HashSet<ITable>(); foreach (ListViewItem item in listViewColumns.CheckedItems) tables.Add(((IColumn)item.Tag).Parent); StringBuilder sb = new StringBuilder(100); for (int i = 0; i < tables.Count; i++) { sb.Append(tables.ElementAt(i).Name); if (i < tables.Count - 1) sb.Append(", "); } if (MessageBox.Show(this, string.Format("Delete all entities currently mapped to this tables [{0}]?", sb), "Delete mapped entities?", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes) foreach (var table in tables) { var entities = table.MappedEntities().ToList(); for (int i = entities.Count - 1; i >= 0; i--) { var entity = entities[i]; entity.DeleteSelf(); } } foreach (ListViewItem item in listViewColumns.CheckedItems) { IColumn column = (IColumn)item.Tag; Property newProperty = Controller.MappingLayer.OneToOneEntityProcessor.CreatePropertyFromColumn(column); newProperty.Name = newProperty.Name.GetNextName(Entity.Properties.Select(p => p.Name)); Entity.AddProperty(newProperty); newProperty.SetMappedColumn(column); } //if (checkBoxAddReferences.Checked) //{ // var mappedEntities = SelectedTable.MappedEntities(); // if (mappedEntities.Count() == 1) // { // if (mappedEntities.ElementAt(0).MappedTables().Count() == 1) // } //} } Close(); }
static void Main(string[] args) { String text = "This is a simple text that count unique words . And this is the text that must be checked"; HashSet<String> words = new HashSet<string>(); String[] differentWords = text.Split(' '); for(int i=0;i<differentWords.Length;i++) { words.Add(differentWords[i]); } Console.WriteLine("Here are all the unique words : "); for(int i=0;i<words.Count;i++) { Console.WriteLine(words.ElementAt(i)); } }
static void Main(string[] args) { string text = "Example test example list Example is here"; HashSet<string> uniqueWords = new HashSet<string>(); string[] storage = text.ToLower().Split(' '); for (int i = 0; i < storage.Length; i++) { uniqueWords.Add(storage[i]); } for (int i = 0; i < uniqueWords.Count; i++) { Console.WriteLine(uniqueWords.ElementAt(i)); } }
/// <summary> /// Get node collection from dataGridView /// </summary> /// <returns>HashSet of nodes</returns> public HashSet<Node> GetNodes() { HashSet<Node> Nodes = new HashSet<Node>(); // Enlist all nodes for (int row = 0; row < dataTable.Rows.Count; row++) Nodes.Add(new Node((string)dataTable.Rows[row][0], (int)dataTable.Rows[row][1])); // Create dependencies for (int row = 0; row < dataTable.Rows.Count; row++) if (dataTable.Rows[row][2] != null) foreach (string dependency in dataTable.Rows[row][2].ToString().Split(separators, StringSplitOptions.RemoveEmptyEntries)) Nodes.ElementAt(row).Dependencies.Add(Nodes.Single(new Func<Node, bool>(delegate(Node node) { return node.ID == dependency; }))); return Nodes; }
public string GetWords() { JavaScriptSerializer serializer = new JavaScriptSerializer(); TrollResponse troll = new TrollResponse(); Random rand = new Random(); /** choose a text file at random to give to the client **/ int textFilename = rand.Next(0, 5); string text = File.ReadAllText("../../Text/" + textFilename + ".txt"); /** **/ /** split text on different punctuations **/ char[] separators = {'.', ' ', ',', '!', ';', '-'}; string[] wordsInText = text.Split(separators, StringSplitOptions.RemoveEmptyEntries); /** **/ /** create a set of unique words in the text **/ HashSet<string> uniqueWords = new HashSet<string>(StringComparer.CurrentCultureIgnoreCase); foreach (string word in wordsInText) { uniqueWords.Add(word); } /** **/ int len = uniqueWords.Count; troll.Text = text; /** if there is only one unique word in text exclude word list will be empty **/ if (len == 1) { return serializer.Serialize(troll); } /** **/ /** select words to be excluded from count at random **/ int excludeLen = rand.Next(0, len - 1); HashSet<string> excludeList = new HashSet<string>(); for (int i = 0; i < excludeLen; i++) { excludeList.Add(uniqueWords.ElementAt(rand.Next(0 , len - 1))); } troll.Exclude = excludeList.ToArray(); /** **/ return serializer.Serialize(troll); }
public ListBookings(Welcome welcomeForm, OdbcConnection odbcConnection, HashSet<BookingInformation> bookings) : this() { objectWelcomeForm = welcomeForm; objectOdbcConnection = odbcConnection; bookingsListView.Columns.Add("Guest ID"); bookingsListView.Columns.Add("First Name"); bookingsListView.Columns.Add("Last Name"); bookingsListView.Columns.Add("Phone"); bookingsListView.Columns.Add("CheckIn Date"); bookingsListView.Columns.Add("CheckOut Date"); bookingsListView.Columns.Add("Room Number"); bookingsListView.Columns.Add("Booking Status"); bookingsListView.Columns[0].Width = 100; bookingsListView.Columns[1].Width = 125; bookingsListView.Columns[2].Width = 125; bookingsListView.Columns[3].Width = 100; bookingsListView.Columns[4].Width = 80; bookingsListView.Columns[5].Width = 80; bookingsListView.Columns[6].Width = 80; bookingsListView.Columns[7].Width = 100; //bookingsListBox.Items.Add(lv); for(int i= 0; i<bookings.Count; i++) { string[] listColumns = new string[8]; listColumns[0] = bookings.ElementAt(i).bookedGuest.guestId; listColumns[1] = bookings.ElementAt(i).bookedGuest.firstName; listColumns[2] = bookings.ElementAt(i).bookedGuest.lastName; listColumns[3] = bookings.ElementAt(i).bookedGuest.phone; listColumns[4] = bookings.ElementAt(i).checkInDate.ToShortDateString(); listColumns[5] = bookings.ElementAt(i).checkOutDate.ToShortDateString(); listColumns[6] = bookings.ElementAt(i).bookedRoom.roomNumber; listColumns[7] = bookings.ElementAt(i).status; ListViewItem li = new ListViewItem(listColumns); if (i % 2 == 0) { li.BackColor = Color.Gainsboro; } bookingsListView.Items.Add(li); } }
static void Main(string[] args) { int arr0 = 1, arr1 = 2; List<long> listArr0 = new List<long>(); List<long> f2 = new List<long>(); List<long> f3 = new List<long>(); listArr0.Add(arr0); f2.Add(arr1); f3.Add(arr1); // do utre nema go smetne tva sus 1 000 000 + tova toq long prevurta-> taka 4e go praa do 50 for(int i=1;i<50;i++) { listArr0.Add(((2*listArr0.ElementAt(i-1))+3)); f2.Add(((3*f2.ElementAt(i-1))+1)); f3.Add(((2*f3.ElementAt(i-1))-1)); } // obedinenie HashSet<long> obedinenie = new HashSet<long>(); for(int i=0;i<50;i++) { obedinenie.Add(listArr0.ElementAt(i)); obedinenie.Add(f3.ElementAt(i)); } //se4enie HashSet<long> sechenie = new HashSet<long>(); for(int i=0;i<50;i++) { if(listArr0.Contains(f3.ElementAt(i))) { sechenie.Add(f3.ElementAt(i)); } } Console.WriteLine("Obedinenie : "); for(int i=0;i<obedinenie.Count;i++) { Console.WriteLine(" " + obedinenie.ElementAt(i) + " "); } Console.WriteLine("Se4enie : "); for(int i=0;i<sechenie.Count;i++) { Console.WriteLine(" " + sechenie.ElementAt(i) + " "); } }
/// <summary> /// Метод возвращает массив, описывающий ритм /// </summary> /// <param name="segmentsCount">Количество долей в такте (количество нот и пауз)</param> /// <param name="notesCount">Количество звучащих нот</param> /// <returns></returns> public static int[] GetRhythm(int segmentsCount, int notesCount) { HashSet<int> set = new HashSet<int>(); for (int i = 0; i < segmentsCount; i++) { set.Add(i); } int[] rhythm = new int[segmentsCount]; Random rand = new Random(); for (int i = 0; i < notesCount; i++) { int pos = rand.Next(0, segmentsCount); int position = set.ElementAt(pos); rhythm[position] = 1; set.Remove(position); segmentsCount--; } return rhythm; }
public Chunk(Vector3 position) { this.BlockPositions = new Block[ChunkSize, ChunkSize, ChunkSize]; this.Position = position * ChunkSize; this.uniqueBlocks = new HashSet<Block>(); this.uniqueBlocks.Add(new Block("checkerboard")); this.uniqueBlocks.Add(new Block("stone")); Random rnd = new Random(); for (int x = 0; x < ChunkSize; x++) { for (int z = 0; z < ChunkSize; z++) { int maxY = rnd.Next(1, 4); for (int y = 0; y <= maxY; y++) { this.BlockPositions[x, y, z] = uniqueBlocks.ElementAt(0); } } } this.Mesh = GenerateMesh(); this.Effects = new HashSet<Effect>(); foreach (Block b in this.uniqueBlocks) { BasicEffect effect = new BasicEffect(Game1.Instance.GraphicsDevice); effect.TextureEnabled = true; effect.Texture = b.Texture; this.Effects.Add(effect); b.Effects.Add(effect); } }
static List<HashSet<int>> GetAllSubsetsHelper(int n, HashSet<int> s) { List<HashSet<int>> list = new List<HashSet<int>>(); if (s.Count == 0) { list.Add(new HashSet<int>()); HashSet<int> withN = new HashSet<int>(); withN.Add(n); list.Add(withN); return list; } int element = s.ElementAt(0); s.Remove(element); list = GetAllSubsetsHelper(element,s); List<HashSet<int>> secondList = new List<HashSet<int>>(); for(int i = 0;i<list.Count;i++) { HashSet<int> newSet = new HashSet<int>(list.ElementAt<HashSet<int>>(i)); newSet.Add(n); secondList.Add(newSet); } list.AddRange(secondList); return list; }
public void AktualizatorBrzeżnościKomórekOdpowiednioPrzypisujeBrzeżnościKomórek(int indeksInicjatora, BrzeznoscKomorki spodziewanaBrzeznoscK1, BrzeznoscKomorki spodziewanaBrzeznoscK2, BrzeznoscKomorki spodziewanaBrzeznoscK3, BrzeznoscKomorki spodziewanaBrzeznoscK4, BrzeznoscKomorki spodziewanaBrzeznoscK5) { _komorki = MockKomorek(); IMapa mapa = MockKlasyMapa(_komorki); IKomorka inicjator = _komorki.ElementAt(indeksInicjatora); var rozdzielacz = new RozdzielaczMorzIJezior(inicjator) { Nastepnik = new AktualizatorBrzeznosciKomorek() }; mapa.ZastosujPrzetwarzanie(rozdzielacz); _komorki.ElementAt(0).Dane.Brzeznosc.ShouldEqual(spodziewanaBrzeznoscK1); _komorki.ElementAt(1).Dane.Brzeznosc.ShouldEqual(spodziewanaBrzeznoscK2); _komorki.ElementAt(2).Dane.Brzeznosc.ShouldEqual(spodziewanaBrzeznoscK3); _komorki.ElementAt(3).Dane.Brzeznosc.ShouldEqual(spodziewanaBrzeznoscK4); _komorki.ElementAt(4).Dane.Brzeznosc.ShouldEqual(spodziewanaBrzeznoscK5); }
// admin deletearea x y z radius public override bool HandleCommand(ulong userId, string[] words) { HashSet<IMyEntity> entities = new HashSet<IMyEntity>(); HashSet<IMyEntity> entitiesToConfirm = new HashSet<IMyEntity>(); HashSet<IMyEntity> entitiesConnected = new HashSet<IMyEntity>(); HashSet<IMyEntity> entitiesFound = new HashSet<IMyEntity>(); Wrapper.GameAction(() => { MyAPIGateway.Entities.GetEntities(entities, x => x is IMyCubeGrid); }); foreach (IMyEntity entity in entities) { if (!(entity is IMyCubeGrid)) continue; IMyCubeGrid grid = (IMyCubeGrid)entity; MyObjectBuilder_CubeGrid gridBuilder = CubeGrids.SafeGetObjectBuilder(grid); if (gridBuilder == null) continue; bool found = false; foreach (MyObjectBuilder_CubeBlock block in gridBuilder.CubeBlocks) { if (block.TypeId == typeof(MyObjectBuilder_Beacon)) { found = true; break; } } if (!found) entitiesToConfirm.Add(grid); } CubeGrids.GetGridsUnconnected(entitiesFound, entitiesToConfirm); foreach (IMyEntity entity in entitiesFound) { CubeGridEntity gridEntity = (CubeGridEntity)GameEntityManager.GetEntity(entity.EntityId); if (gridEntity == null) { Log.Info("A found entity gridEntity was null!"); continue; } Communication.SendPrivateInformation(userId, string.Format("Found entity '{0}' ({1}) at {2} with no beacon.", gridEntity.Name, entity.EntityId, General.Vector3DToString(entity.GetPosition()))); } for(int r = entitiesFound.Count - 1; r >= 0; r--) { //MyAPIGateway.Entities.RemoveEntity(entity); IMyEntity entity = entitiesFound.ElementAt(r); CubeGridEntity gridEntity = new CubeGridEntity((MyObjectBuilder_CubeGrid)entity.GetObjectBuilder(), entity); gridEntity.Dispose(); } Communication.SendPrivateInformation(userId, string.Format("Removed {0} grids with no beacons", entitiesFound.Count)); return true; }
// forced static private static Bgr extractPointColor(Point p, Mat input) { HashSet<Bgr> nearbyColors = new HashSet<Bgr>(); for (int i = p.X - Constants.AREA_SHIFT; i <= p.X + Constants.AREA_SHIFT; i++) { for (int j = p.Y - Constants.AREA_SHIFT; j <= p.Y + Constants.AREA_SHIFT; j++) { if (i >= 0 && i < input.Width) { if (j >= 0 && j < input.Height) { nearbyColors.Add(new Bgr(input.GetData(j, i)[0], input.GetData(j, i)[1], input.GetData(j, i)[2])); } } } } // check the whiteness of nearby pixels, use the less whiteness pixel as edge color double maxWhiteness = 0; // check max int index = 0; int maxIndex = 0; foreach (Bgr c in nearbyColors) { double whiteness = Metrics.Whiteness(c); if (whiteness > maxWhiteness) { maxWhiteness = whiteness; maxIndex = index; } index++; } //Color ccolor = Color.FromArgb((int)color.Red, (int)color.Green, (int)color.Blue); return nearbyColors.ElementAt(maxIndex); }
//Validate that the we are using valid colors and set appropriate defaults if not. private void CheckForInvalidColorData() { // check for sane default colors when first rendering it HashSet<Color> validColors = new HashSet<Color>(); validColors.AddRange(TargetNodes.SelectMany(x => ColorModule.getValidColorsForElementNode(x, true))); //Validate Color 1 if (validColors.Any() && (!validColors.Contains(_data.Color1.ToArgb()) || !_data.ColorGradient1.GetColorsInGradient().IsSubsetOf(validColors))) { Color1 = validColors.First(); ColorGradient1 = new ColorGradient(validColors.First()); } //Validate color 2 if (validColors.Any() && (!validColors.Contains(_data.Color2.ToArgb()) || !_data.ColorGradient2.GetColorsInGradient().IsSubsetOf(validColors))) { if (validColors.Count > 1) { Color2 = validColors.ElementAt(1); ColorGradient2 = new ColorGradient(validColors.ElementAt(1)); } else { Color2 = validColors.First(); ColorGradient2 = new ColorGradient(validColors.First()); } } }
private void nomeAnexos_DoubleClick(object sender, EventArgs e) { if (!String.IsNullOrEmpty(nomeAnexos.Text)) { int selInicio = nomeAnexos.SelectionStart; int selFim = nomeAnexos.Text.IndexOf(";", selInicio); int selTamanho = selFim - selInicio; string nome = nomeAnexos.Text.Substring(selInicio, selTamanho); nomeAnexos.SelectionStart = selInicio; nomeAnexos.SelectionLength = selTamanho; string[] listArq = nomeAnexos.Text.Split(';'); int listCount = 0; int count = 0; int listCountInicio = 0; int listCountFim = 0; foreach (string arq in listArq) { listCountFim += arq.Trim().Length + 2; if (arq.Contains(nome) && listCountInicio <= selInicio && listCountFim > selInicio) { nome = arq.Trim(); selInicio = listCountInicio; break; } listCountInicio = listCountFim; } if (control == 1) { if(nome.Contains(".sac")) nome = gerenciaServlet.recuperaNomeOriginalArquivo(nome); System.Diagnostics.Process.Start(caminho + nome); } else { HashSet<string> files = new HashSet<string>(); if(CriptoFiles != null) foreach(string path in CriptoFiles) files.Add(path); if(PlainFiles != null) foreach(string path in PlainFiles) files.Add(path); foreach (string file in files) { if (file.Contains(nome) && count == selInicio) { nome = files.ElementAt(listCount); break; } count += gerenciaServlet.retornaNome(file).Length + 2; listCount++; } System.Diagnostics.Process.Start(nome); } } }
/** * Call this function to make the computer play a move. */ private void BotMove() { // TODO - Change this function so the computer can play against you // Enumerate through the grid, check for open spots HashSet<Tuple<int, int>> possibleMoves = new HashSet<Tuple<int, int>>(); for (int i = 0; i < GAME_GRID_ROWS_COUNT; i++) { for (int j = 0; j < GAME_GRID_COLUMNS_COUNT; j++) { if (gameGrid.GetGrid(i, j) == EMPTY_VALUE) { possibleMoves.Add(Tuple.Create(i, j)); } } } // Check if there are possible moves if (possibleMoves.Count == 0) { // No possible moves, game is a tie isGameOver = true; ShowPopup("Tie Game!", 90); } else { // Randomly choose a move int moveIndex = (new Random()).Next(possibleMoves.Count); Tuple<int, int> move = possibleMoves.ElementAt(moveIndex); gameGrid.SetGrid(move.Item1, move.Item2, BOT_VALUE); } }
private static Dictionary<int, byte> GetColors(int width, int height, ref int[,] labels, int[,] borders) { for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { int basePoint = labels[x, y]; if (borders[x, y] == 1 && basePoint != 0) { int curPoint = 0; if (x > 0) { curPoint = labels[x - 1, y]; if (curPoint != 0 && curPoint != basePoint) { UniteColors(width, height, ref labels, basePoint, curPoint); continue; } } if (x > 0 && y > 0) { curPoint = labels[x - 1, y - 1]; if (curPoint != 0 && curPoint != basePoint) { UniteColors(width, height, ref labels, basePoint, curPoint); continue; } } if (y > 0) { curPoint = labels[x, y - 1]; if (curPoint != 0 && curPoint != basePoint) { UniteColors(width, height, ref labels, basePoint, curPoint); continue; } } if (x < width - 1 && y > 0) { curPoint = labels[x + 1, y - 1]; if (curPoint != 0 && curPoint != basePoint) { UniteColors(width, height, ref labels, basePoint, curPoint); continue; } } if (x < width - 1) { curPoint = labels[x + 1, y]; if (curPoint != 0 && curPoint != basePoint) { UniteColors(width, height, ref labels, basePoint, curPoint); continue; } } if (x < width - 1 && y < height - 1) { curPoint = labels[x + 1, y + 1]; if (curPoint != 0 && curPoint != basePoint) { UniteColors(width, height, ref labels, basePoint, curPoint); continue; } } if (y < height - 1) { if (labels[x, y + 1] != 0 && labels[x, y + 1] != basePoint) { UniteColors(width, height, ref labels, basePoint, curPoint); continue; } } if (x > 0 && y < height - 1) { curPoint = labels[x - 1, y + 1]; if (curPoint != 0 && curPoint != basePoint) { UniteColors(width, height, ref labels, basePoint, curPoint); continue; } } } } } var hashSet = new HashSet<int>(); for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { hashSet.Add(labels[x, y]); } } var colors = new Dictionary<int, byte>(); byte curColor = 0; for (int i = 0; i < hashSet.Count; i++) { int hashElement = hashSet.ElementAt(i); colors.Add(hashElement, (hashElement == 0) ? (byte)255 : curColor); curColor += 20; if (curColor > 230) { curColor = 0; } } return colors; }
/// <summary> /// temporarily flips joints to remove cycles /// </summary> private void RemoveGraphCycles() { HashSet<GraphNode> tempGraph = new HashSet<GraphNode>(RobotNodes.Values.ToArray()); while (tempGraph.Count > 0) { bool hasFinished = false; while (!hasFinished)//remove all sources from tempGraph. A source is a node with no parents { hasFinished = true; GraphNode tempNode; for (int i = 0; i < tempGraph.Count;i++ ) { tempNode = tempGraph.ElementAt(i); if(!tempGraph.Overlaps(tempNode.ParentNodes)) { tempGraph.Remove(tempNode); hasFinished = false; i--; } } } hasFinished = false; while (!hasFinished)//remove all sinks from the graph. A sink is a node with no children { hasFinished = true; GraphNode tempNode; for (int i = 0; i < tempGraph.Count; i++) { tempNode = tempGraph.ElementAt(i); if(!tempGraph.Overlaps(tempNode.ChildNodes)) { tempGraph.Remove(tempNode); hasFinished = false; i--; } } } if (tempGraph.Count > 0) //If nodes are left, they must be in a cycle, so flip joints to fix { foreach (GraphNode tempNode in tempGraph) { if (tempNode.Equals(RobotNodes[0]) || tempNode.ParentNodes.Count > 1) { List<GraphNode> tempList = tempNode.ParentNodes.ToList(); foreach (GraphNode g in tempList) { if (tempGraph.Contains(g)) { tempNode.FlipJoint(g); } } break; } } } } }
private HashSet<IRog> MockRogow(HashSet<IKomorka> komorki) { var r1 = new Rog{ Punkt = new Punkt()}; var r2 = new Rog{ Punkt = new Punkt()}; var r3 = new Rog{ Punkt = new Punkt()}; var r4 = new Rog{ Punkt = new Punkt()}; var r5 = new Rog{ Punkt = new Punkt()}; r1.BliskieRogi = new List<IRog> { r2, r3 }; r2.BliskieRogi = new List<IRog> { r1, r3, r4 }; r3.BliskieRogi = new List<IRog> { r1, r2, r5 }; r4.BliskieRogi = new List<IRog> { r2, r5 }; r5.BliskieRogi = new List<IRog> { r3, r4 }; r1.Komorki = new List<IKomorka> {komorki.ElementAt(0), komorki.ElementAt(1)}; r2.Komorki = new List<IKomorka> {komorki.ElementAt(1), komorki.ElementAt(2)}; r3.Komorki = new List<IKomorka> {komorki.ElementAt(1), komorki.ElementAt(3)}; r4.Komorki = new List<IKomorka> {komorki.ElementAt(2), komorki.ElementAt(4)}; r5.Komorki = new List<IKomorka> {komorki.ElementAt(3), komorki.ElementAt(4)}; komorki.ElementAt(0).Rogi = new List<IRog> {r1}; komorki.ElementAt(1).Rogi = new List<IRog> {r1, r2, r3}; komorki.ElementAt(2).Rogi = new List<IRog> {r2, r4}; komorki.ElementAt(3).Rogi = new List<IRog> {r3, r5}; komorki.ElementAt(4).Rogi = new List<IRog> {r4, r5}; komorki.ElementAt(0).Punkt.Sasiedzi = komorki.ElementAt(0).Rogi.Select(r => r.Punkt).ToList(); komorki.ElementAt(1).Punkt.Sasiedzi = komorki.ElementAt(1).Rogi.Select(r => r.Punkt).ToList(); komorki.ElementAt(2).Punkt.Sasiedzi = komorki.ElementAt(2).Rogi.Select(r => r.Punkt).ToList(); komorki.ElementAt(3).Punkt.Sasiedzi = komorki.ElementAt(3).Rogi.Select(r => r.Punkt).ToList(); komorki.ElementAt(4).Punkt.Sasiedzi = komorki.ElementAt(4).Rogi.Select(r => r.Punkt).ToList(); r1.Punkt.Sasiedzi = r1.BliskieRogi.Select(b => b.Punkt).Union(r1.Komorki.Select(k => k.Punkt)).ToList(); r2.Punkt.Sasiedzi = r2.BliskieRogi.Select(b => b.Punkt).Union(r2.Komorki.Select(k => k.Punkt)).ToList(); r3.Punkt.Sasiedzi = r3.BliskieRogi.Select(b => b.Punkt).Union(r3.Komorki.Select(k => k.Punkt)).ToList(); r4.Punkt.Sasiedzi = r4.BliskieRogi.Select(b => b.Punkt).Union(r4.Komorki.Select(k => k.Punkt)).ToList(); r5.Punkt.Sasiedzi = r5.BliskieRogi.Select(b => b.Punkt).Union(r5.Komorki.Select(k => k.Punkt)).ToList(); return new HashSet<IRog>{r1, r2, r3, r4, r5}; }
public void WyrównywaczTerenuWodyOdpowiednioModyfikujeWysokosc(string wodne, float minWys) { _komorki = MockKomorek(); _rogi = MockRogow(_komorki); IMapa mapa = MockKlasyMapa(_komorki, _rogi); _komorki.ToList().ForEach(k => k.Dane.Podloze = Podloze.Ziemia); _komorki.ToList().ForEach(k => k.Dane.Typ = TypKomorki.Lad); for (int i = 0; i < 5; ++i) // wysokość punktu = jego numer { _komorki.ElementAt(i).Punkt.Wysokosc = i + 1; _rogi.ElementAt(i).Punkt.Wysokosc = i + 1; } IEnumerable<int> indeksyWodnych = wodne.Split(';').Select(n => int.Parse(n) - 1); foreach (int indeks in indeksyWodnych) _komorki.ElementAt(indeks).Dane.Podloze = Podloze.Woda; mapa.ZastosujPrzetwarzanie(new WyrownywaczTerenuWody(minWys)); List<IKomorka> doSprawdzenia = _komorki.Where((k, indeks) => indeksyWodnych.Contains(indeks)).ToList(); doSprawdzenia.ForEach(k => k.Punkt.Wysokosc.ShouldEqual(minWys)); // niepotrzebne? doSprawdzenia.ForEach(ds => ds.Rogi.ToList().ForEach(r => r.Punkt.Wysokosc.ShouldEqual(minWys))); }
public void RozdzielaczMorzIJeziorOdpowiednioPrzypisujeTypyDlaDwóchInicjatorów() { _komorki = MockKomorek(); IMapa mapa = MockKlasyMapa(_komorki); IKomorka inicjator1 = _komorki.ElementAt(0); IKomorka inicjator2 = _komorki.ElementAt(4); IPrzetwarzaczMapy rozdzielacz = new RozdzielaczMorzIJezior(new IKomorka[]{inicjator1, inicjator2}); mapa.ZastosujPrzetwarzanie(rozdzielacz); _komorki.ElementAt(0).Dane.Typ.ShouldEqual(TypKomorki.Morze); _komorki.ElementAt(1).Dane.Typ.ShouldEqual(TypKomorki.Morze); _komorki.ElementAt(2).Dane.Typ.ShouldEqual(TypKomorki.Lad); _komorki.ElementAt(3).Dane.Typ.ShouldEqual(TypKomorki.Lad); _komorki.ElementAt(4).Dane.Typ.ShouldEqual(TypKomorki.Morze); }
public void RozdzielaczMorzIJeziorOdpowiednioPrzypisujeTypy(int indeksInicjatora, TypKomorki spodziewanyTypK1, TypKomorki spodziewanyTypK2, TypKomorki spodziewanyTypK3, TypKomorki spodziewanyTypK4, TypKomorki spodziewanyTypK5) { _komorki = MockKomorek(); IMapa mapa = MockKlasyMapa(_komorki); IKomorka inicjator = _komorki.ElementAt(indeksInicjatora); IPrzetwarzaczMapy rozdzielacz = new RozdzielaczMorzIJezior(inicjator); mapa.ZastosujPrzetwarzanie(rozdzielacz); _komorki.ElementAt(0).Dane.Typ.ShouldEqual(spodziewanyTypK1); _komorki.ElementAt(1).Dane.Typ.ShouldEqual(spodziewanyTypK2); _komorki.ElementAt(2).Dane.Typ.ShouldEqual(spodziewanyTypK3); _komorki.ElementAt(3).Dane.Typ.ShouldEqual(spodziewanyTypK4); _komorki.ElementAt(4).Dane.Typ.ShouldEqual(spodziewanyTypK5); }
public ArrayList manageCpuApp(String file, String cpu_app_stat) { ArrayList ret = new ArrayList(); ArrayList ret2 = new ArrayList(); int countLine = CPU_cores; string[] cpu_app_stats = File.ReadAllLines(file + cpu_app_stat); bool inLoop = false; for (int i = 0; i < cpu_app_stats.Length; i++) { if (cpu_app_stats[i].Contains("+++")) { inLoop = true; continue; } if (cpu_app_stats[i].Trim().Equals("")) { inLoop = false; //check cpu num match int len1 = ret.Count; HashSet<string> cpuSets = new HashSet<string>(); for (int b = 0; b < len1; b++) { string[] str = ret[b].ToString().Split(' '); string cpuNum = str[38]; cpuSets.Add(cpuNum); } Dictionary<string, int[]> match = new Dictionary<string, int[]>(); //initial match for (int c = 0; c < cpuSets.Count; c++) { match[cpuSets.ElementAt<string>(c)] = new int[] { 0, 0 }; } for (int c = 0; c < cpuSets.Count; c++) { string cpuType = cpuSets.ElementAt<string>(c); for (int d = 0; d < ret.Count; d++) { string[] str = ret[d].ToString().Split(' '); string cpuNum = str[38]; if (cpuNum.Equals(cpuType)) { int[] s = new int[2]; s[0] = int.Parse(str[13]); s[1] = int.Parse(str[14]); match[cpuType][0] += s[0]; match[cpuType][1] += s[1]; } } } for (int a = 0; a < 8; a++) { if (match.ContainsKey(a.ToString())) { // ret2.Add(match[a.ToString()][0] + " " + match[a.ToString()][1]); string s = match[a.ToString()][0] + " " + match[a.ToString()][1]; ret2.Add(s); } else { ret2.Add("0"); } } ret.Clear(); continue; } if (inLoop) { ret.Add(cpu_app_stats[i]); } } return ret2; }
/// <summary> /// Searches the player's current location, their inventory, and their /// clothes for a thing with the specified name. /// </summary> /// <param name="name">the name of the thing</param> /// <returns>a thing with the specified name, if it is found; null if none is found</returns> private static Thing findThingNamed(string name) { HashSet<Thing> itemsFound = new HashSet<Thing>(); foreach (Thing item in GetTopMostVisibleContainer(player.GetLocation()).GetVisibleRecursiveContents()) { if (item.IsNamed(name)) { itemsFound.Add(item); } } foreach (Thing item in player.GetRecursiveContents()) { if (item.IsNamed(name)) { itemsFound.Add(item); } } if (itemsFound.Count == 0) { return null; } else if (itemsFound.Count == 1) { return itemsFound.ElementAt(0); } else { Console.WriteLine("The specified name is ambiguous. Try being more specific?"); Console.Write(">>> "); return findThingNamed(Console.ReadLine()); } }