public void MethodUnderTest_TestedBehavior_ExpectedResult() { var nodeList = new LinkedList<object>(); nodeList.Add(new ListNode<object>(1)); nodeList.Add(new ListNode<object>(2)); nodeList.Add(new ListNode<object>(3)); nodeList.Add(new ListNode<object>(4)); nodeList.Add(new ListNode<object>(5)); nodeList.Add(new ListNode<object>(6)); nodeList.Add(new ListNode<object>("d")); nodeList.Add(new ListNode<object>("g")); nodeList.AddAfter(3, new ListNode<object>("B")); nodeList.AddAfter("g", new ListNode<object>("uber")); Console.WriteLine(nodeList.Tail); Console.WriteLine("The list has {0} elements!", nodeList.ListSize); nodeList.Traverse(); nodeList.Reverse(); nodeList.Traverse(); Assert.That(nodeList.ListSize, Is.EqualTo(10)); Assert.That(nodeList.Contains("g"), Is.True); nodeList.Remove("d"); nodeList.Remove("g"); Assert.That(nodeList.ListSize, Is.EqualTo(8)); Assert.That(nodeList.Contains("g"), Is.False); nodeList.Reverse(); nodeList.Traverse(); }
public void ContainsInt() { var target = new LinkedList<int>() { 1, 2, 3 }; Assert.IsTrue(target.Contains(1)); Assert.IsTrue(target.Contains(2)); Assert.IsTrue(target.Contains(3)); Assert.IsFalse(target.Contains(0)); }
public void ContainsTest() { var list = new LinkedList<string>(); Assert.IsTrue(list != null); list.Add("first item"); Assert.IsTrue(list.Contains("first item")); Assert.IsFalse(list.Contains("second item")); }
// Implement the data structure linked list. public static void Main() { var linkedList = new LinkedList<string>(); linkedList.AddFirst("first"); linkedList.AddLast("second"); Console.WriteLine(string.Join(", ", linkedList)); linkedList.Clear(); linkedList.AddLast("second"); linkedList.AddFirst("first"); Console.WriteLine(string.Join(", ", linkedList)); string value = "first"; Console.WriteLine("List contains \"{0}\": {1}", value, linkedList.Contains(value)); Console.WriteLine("List contains {0} item(s)", linkedList.Count); var item = linkedList.Find("second"); Console.WriteLine(item); linkedList.Remove("first"); Console.WriteLine(string.Join(", ", linkedList)); linkedList.Remove("second"); Console.WriteLine("List contains {0} item(s): {1}", linkedList.Count, string.Join(", ", linkedList)); linkedList.AddFirst("second"); linkedList.AddFirst("first"); linkedList.AddLast("third"); Console.WriteLine(string.Join(", ", linkedList)); linkedList.Remove("second"); Console.WriteLine(string.Join(", ", linkedList)); }
static void Main() { var list = new LinkedList<int>(); list.AddLast(1); Console.WriteLine(list); list.AddLast(2); Console.WriteLine(list); list.AddLast(3); Console.WriteLine(list); list.AddFirst(-1); Console.WriteLine(list); list.AddFirst(-2); Console.WriteLine(list); list.AddFirst(-3); Console.WriteLine(list); Console.WriteLine("Remove First: {0}", list.RemoveFirst().Value); Console.WriteLine("Remove Last: {0}", list.RemoveLast().Value); Console.WriteLine(list); Console.WriteLine("Min: {0}; Max: {1}", list.Min(), list.Max()); Console.WriteLine("Contains 2: {0}", list.Contains(2)); Console.WriteLine("Count: {0}", list.Count); }
public void ContainsWithEmptyListTest() { var list = new LinkedList<string>(); Assert.IsTrue(list != null); Assert.IsFalse(list.Contains("test")); }
private void ValidateMapping(Type service, LinkedList<Type> breadcrumbs) { if (breadcrumbs.Contains(service)) throw new CircularDependenciesException( "Found a circular dependency when looking up " + breadcrumbs.First() + ", when inspecting the constructor of " + breadcrumbs.Last() + ", violating service: " + service, breadcrumbs); IList<IBuildPlan> buildPlans; if (!_serviceMappings.TryGetValue(service, out buildPlans)) throw new DependencyNotRegisteredException(breadcrumbs.Last.Value, service); var cbp = buildPlans.Last() as ConcreteBuildPlan; if(cbp == null) return; breadcrumbs.AddLast(service); foreach (var parameter in cbp.Constructor.GetParameters()) { ValidateMapping(parameter.ParameterType, breadcrumbs); } breadcrumbs.RemoveLast(); }
static LinkedList<LinkedList<string>> convertToDFA(LinkedList<LinkedList<string>> NFA_Table, LinkedList<string> states, LinkedList<string> finalStates, LinkedList<string> alphabets) { LinkedList<LinkedList<string>> DFA_Table = new LinkedList<LinkedList<string>>(); LinkedList<string> DFA_States = new LinkedList<string>(); string newState=""; DFA_States.AddLast("0"); for (int i = 0; i < DFA_States.Count; i++) { for (int j = 0; j < alphabets.Count; j++) { for (int k = 0; k < NFA_Table.Count; k++) { if (NFA_Table.ElementAt(k).ElementAt(0).CompareTo(DFA_States.ElementAt(i)) == 0 && NFA_Table.ElementAt(k).ElementAt(2).CompareTo(alphabets.ElementAt(j)) == 0) { newState += NFA_Table.ElementAt(i).ElementAt(1); } } if (DFA_States.Contains(newState) == false) { DFA_States.AddLast(newState); LinkedList<string> DFA_Contacts = new LinkedList<string>(); DFA_Contacts.AddLast(DFA_States.ElementAt(i)); DFA_Contacts.AddLast(newState); DFA_Contacts.AddLast(alphabets.ElementAt(j)); DFA_Table.AddLast(DFA_Contacts); } newState = ""; } } return DFA_Table; }
private static void Main() { var linkedList = new LinkedList<int>(); Console.WriteLine(linkedList.Count); Console.WriteLine(linkedList.Contains(1)); linkedList.AddFirst(1); Console.WriteLine(linkedList.Count); }
public void Find_Missing(int[] testData, int value) { LinkedList<int> list = new LinkedList<int>(); foreach (int data in testData) { list.AddLast(new LinkedListNode<int>(data)); } Assert.IsFalse(list.Contains(value), "Nothing should have been found."); }
public LinkedList<string> CollectTerms(LinkedList<string> terms, LinkedList<string> userTerms) { LinkedList<string> newTerms= new LinkedList<string>(); foreach (string term in userTerms) { if (!terms.Contains(term)) newTerms.AddLast(term); } return newTerms; }
public void Find_Found(int[] testData, int value) { LinkedList<int> list = new LinkedList<int>(); foreach (int data in testData) { list.AddLast(new LinkedListNode<int>(data)); } Assert.IsTrue(list.Contains(value), "There should have been a node found"); }
public static void Main(string[] args) { SequenceParser.WarningMessage(); LinkedList<int> sampleList = new LinkedList<int>(); sampleList.Add(-33); sampleList.Add(2); sampleList.Add(100); sampleList.Add(4); foreach (var item in sampleList) { Console.WriteLine(item); } Console.WriteLine(new string('=', 40)); Console.WriteLine($"First element : {sampleList.FirstElement.Value}"); Console.WriteLine($"Last element : {sampleList.LastElement.Value}"); Console.WriteLine($"Count of all elements added : {sampleList.Count}"); Console.WriteLine(new string('=', 40)); var head = sampleList.GetFirstNode(); Console.WriteLine(head.Value); Console.WriteLine(head.NextItem.Value); Console.WriteLine(head.NextItem.NextItem.Value); Console.WriteLine(head.NextItem.NextItem.NextItem.Value); Console.WriteLine(new string('=', 40)); var head2 = head.GetNextNode(); Console.WriteLine(head2.Value); Console.WriteLine(new string('=', 40)); var containsCheckOne = sampleList.Contains(-33); var containsCheckTwo = sampleList.Contains(-3300); Console.WriteLine($"do sample list contains -33 : {containsCheckOne}"); Console.WriteLine($"do sample list contains -3300 : {containsCheckTwo}"); sampleList.Remove(-33); Console.WriteLine(sampleList.GetFirst()); Console.WriteLine(sampleList.LastElement.Value); }
public LinkedList<Ele> del_ele(LinkedList<Ele> d_list, LinkedListNode<Ele> d_ele) { //PexAssume.IsNotNullOrEmpty(d_list); //PexAssume.IsNotNull(d_ele); if (d_list != null) { PexAssume.IsFalse(d_list.Contains(null)); if (d_ele != null) { PexAssume.IsTrue(d_list.Contains(d_ele.Value)); PexAssume.IsNotNull(d_ele.List); if (d_ele.List != null) { PexAssume.IsTrue(d_ele.List.Equals(d_list)); } } } LinkedList<Ele> result = Program.del_ele(d_list, d_ele); return result; // TODO: add assertions to method ProgramTest.del_ele(LinkedList`1<Ele>, LinkedListNode`1<Ele>) }
public static void Main() { // Create LinkedList and test its methods ListItem<int> lastElement = new ListItem<int>(5); LinkedList<int> linkedList = new LinkedList<int>(lastElement); ListItem<int> middleElement = new ListItem<int>(2); linkedList.Add(middleElement); ListItem<int> firstElement = new ListItem<int>(-3); linkedList.Add(firstElement); bool contains = linkedList.Contains(firstElement); linkedList.Remove(middleElement); int index = linkedList.IndexOf(lastElement); int count = linkedList.Count(); ListItem<int> element = linkedList[index]; bool isSame = lastElement == element; }
public static LinkedList<Direction> FindPath(FieldMap map, FieldNode start, FieldNode goal) { LinkedList<FieldNode> path = new LinkedList<FieldNode>(); Stack<FieldNode> stack = new Stack<FieldNode>(); stack.Push(start); while (stack.Count > 0) { FieldNode node = stack.Pop(); //AddToPath(path, node); if (node.Equals(goal)) return TranslateToDirections(path); LinkedList<FieldNode> sons = map.findSons(node); //Iterator<Node> iter = sons.descendingIterator(); foreach (FieldNode son in sons) { if (!stack.Contains(son) && !path.Contains(son)) stack.Push(son); } } return null; }
private static void Main() { var testList = new LinkedList<int>(); testList.AddFirst(5); testList.AddFirst(6); testList.AddFirst(7); testList.AddLast(9); foreach (var item in testList) { Console.WriteLine(item); } for (var i = 0; i < testList.Count; i++) { testList[i] = i; Console.WriteLine(testList[i]); } Console.WriteLine(testList.Contains(2)); Console.WriteLine(testList); }
protected internal virtual IQueryable<State> GetFollowingStates([NotNull] State state) { Debug.ArgumentNotNull(state, "state"); ICollection<Tuple<string, SubstateCombinationSet>> stateTransitionInfo = new LinkedList<Tuple<string, SubstateCombinationSet>>(); Dictionary<string, bool> substateCombinationPrototype = state.Substates.ToDictionary(substate => substate.Code, substate => false); Sitecore.Data.Items.Item stateItem = this.GeStateItem(state); if (stateItem != null) { Sitecore.Data.Items.Item[] transitionItems = stateItem.Axes.SelectItems(string.Format("./{0}/*", FollowingStatusesContainerName)); if (transitionItems != null) { foreach (Sitecore.Data.Items.Item transitionItem in transitionItems) { if (((Sitecore.Data.Fields.ReferenceField)transitionItem.Fields[FollowingStateFieldName]).TargetItem != null) { string stateCode = ((Sitecore.Data.Fields.ReferenceField)transitionItem.Fields[FollowingStateFieldName]).TargetItem.Fields[CodeFieldName].Value; stateTransitionInfo.Add(Tuple.Create(stateCode, this.CreateSubstateCombinationSetFromItem(transitionItem, substateCombinationPrototype))); } } } } LinkedList<string> resultingStateCodes = new LinkedList<string>(); foreach (Tuple<string, SubstateCombinationSet> transition in stateTransitionInfo) { if (this.IsSubstateCombinationApplicable(state, transition.Item2)) { resultingStateCodes.AddLast(transition.Item1); } } return this.GetAll(s => resultingStateCodes.Contains(s.Code)); }
public void SaveLevel(string a_fileName, Level a_save) { foreach (LinkedList<GameObject> t_goSaveList in a_save.getGameObjects()) { foreach (GameObject t_go in t_goSaveList) { t_go.saveObject(); } } foreach (LinkedList<GameObject> t_goSaveList in a_save.getGameObjects()) { foreach (GameObject t_go in t_goSaveList) { t_go.linkObject(); } } foreach (Event t_e in a_save.getEvents()) { t_e.linkObject(); } MemoryStream t_stream = null; FileStream t_fstream = null; t_fstream = File.Open("Content//Levels//" + a_fileName, FileMode.Create); BinaryFormatter t_bFormatter = new BinaryFormatter(); LinkedList<string> t_unikName = new LinkedList<string>(); LinkedList<LinkedList<GameObject>> t_objekts = new LinkedList<LinkedList<GameObject>>(); int index = 0; long t_fstreamDiffSize = 0; GameObject.resetGameObjectId(); long t_objectListBegin = t_fstream.Position; t_fstream.Position = t_fstream.Position + 4; long t_fstreamLastPos = t_fstream.Position; long t_objectListSize = t_fstream.Position; foreach (LinkedList<GameObject> t_goList in a_save.getGameObjects()) { t_fstream.Position = t_fstream.Position + 4; foreach(GameObject t_go in t_goList) { if (!t_unikName.Contains(t_go.GetType().Name)) { t_unikName.AddLast(t_go.GetType().Name); t_objekts.AddLast(new LinkedList<GameObject>()); } for (int i = 0; i < t_unikName.Count; ++i) { if (t_unikName.ElementAt<string>(i).Equals(t_go.GetType().Name)) { t_objekts.ElementAt<LinkedList<GameObject>>(i).AddLast(t_go); } } } foreach (LinkedList<GameObject> t_serializeList in t_objekts) { try { t_stream = new MemoryStream(); t_bFormatter.Serialize(t_stream, t_serializeList); byte[] t_msPos = new byte[4]; t_msPos = BitConverter.GetBytes((int)t_stream.Position); t_fstream.Write(t_msPos, 0, t_msPos.Length); t_fstream.Write(t_stream.GetBuffer(), 0, (int)t_stream.Position); } catch (FileNotFoundException) { ErrorLogger.getInstance().writeString("Fail to save serialize, FileNotFound: " + t_serializeList.ElementAt<GameObject>(0)); } catch (SerializationException) { ErrorLogger.getInstance().writeString("Fail to serialize while saving: " + t_serializeList.ElementAt<GameObject>(0)); } if (t_stream != null) { t_stream.Close(); } } byte[] t_layerSize = new byte[4]; t_fstreamDiffSize = t_fstream.Position - t_fstreamLastPos; t_layerSize = BitConverter.GetBytes((int)t_fstreamDiffSize); t_fstream.Position = t_fstream.Position - t_fstreamDiffSize; t_fstream.Write(t_layerSize, 0, t_layerSize.Length); t_objectListSize += t_fstreamDiffSize; t_fstreamLastPos = t_fstream.Length; t_fstream.Position = t_fstream.Length; t_unikName = new LinkedList<string>(); index++; t_objekts = new LinkedList<LinkedList<GameObject>>(); } t_fstream.Position = t_objectListBegin; byte[] t_objectListSizeInByte = new byte[4]; t_objectListSizeInByte = BitConverter.GetBytes((int)t_objectListSize); t_fstream.Write(t_objectListSizeInByte, 0 , t_objectListSizeInByte.Length); t_fstream.Position = t_fstream.Length; if (t_stream != null) { t_stream.Close(); } // Serialize GameObject done! try { //Save Events LinkedList<Event> t_events = a_save.getEvents(); t_stream = new MemoryStream(); t_bFormatter.Serialize(t_stream, t_events); byte[] t_msPos = new byte[4]; t_msPos = BitConverter.GetBytes((int)t_stream.Position); t_fstream.Write(t_msPos, 0, t_msPos.Length); t_fstream.Write(t_stream.GetBuffer(), 0, (int)t_stream.Position); } catch (SerializationException) { ErrorLogger.getInstance().writeString("While saving, failed to serialized event"); } if (t_stream != null) { t_stream.Close(); } //Serialize events done if (t_fstream != null) { t_fstream.Close(); } }
//breadth first search for obtainable spots void testIndividualSpots(ref LinkedList<Vector2> list, int x, int z, int moves, bool origin) { int location = 0; //makes sure the spot is non occupied and accessible TerrainScript t = ground.grid[z,x].GetComponent("TerrainScript") as TerrainScript; if((!t.isAccessible || t.occupied) && !origin) { return; } //add spot if its good if(list.Contains(new Vector2(x,z)) != true) { list.AddLast(new Vector2(x,z)); } if(moves <= 0) { return; } //adds more things to list to check if they are good spots if(x > 0) { t = ground.grid[z,x-1].GetComponent("TerrainScript") as TerrainScript; if(t.isAccessible) { testIndividualSpots(ref list, x - 1, z, moves - t.movementCost, false); } } if(x < ground.xLength - 1) { t = ground.grid[z,x+1].GetComponent("TerrainScript") as TerrainScript; if(t.isAccessible) { testIndividualSpots(ref list, x + 1, z, moves - t.movementCost, false); } } if(z < ground.zLength - 1) { t = ground.grid[z+1,x].GetComponent("TerrainScript") as TerrainScript; if(t.isAccessible) { testIndividualSpots(ref list, x, z + 1, moves - t.movementCost, false); } } if(z > 0) { t = ground.grid[z-1,x].GetComponent("TerrainScript") as TerrainScript; if(t.isAccessible) { testIndividualSpots(ref list, x, z - 1, moves - t.movementCost, false); } } }
protected override void Initialize() { rand=new Random(); missle = new LinkedList<wave>(); missle.Clear(); monster = new LinkedList<enemy>(); monster.Clear(); tree = new LinkedList<Rectangle>(); tree.Clear(); timeSinceLastFrame = 0; timeSinceLastFrame_deading=0; millisecondsPerFrame = 75; millisecondsPerFrame_attacking = 50; millisecondsPerFrame_deading = 150; col=Window.ClientBounds.Width/30; row=Window.ClientBounds.Height/4*3/40; map = new maptype[col, row]; Rectangle temp; //spawning trees for (int i = 0; i < col; i ++) { for (int j = 0; j < row; j++) { temp = new Rectangle(i * 30, j * 40, 30, 40); map[i,j].rect =temp; if(rand.Next(1,100)<5) { map[i,j].ocupied=true; //probably there 489 cell in the whole screen, we let 5% of them are trees randomly tree.AddLast(map[i,j].rect); } else { } } } // spawning monsters which are not in the trees for (int k = 0; k < 5; k++) { int tempX=rand.Next(0,col);int tempY=rand.Next(0,row); if (!tree.Contains(map[tempX,tempY].rect)) { map[tempX,tempY].ocupied=true; monster.AddLast(new enemy(map[tempX,tempY].rect,tree,rand )); } } //spawning hero which is either not in the trees places nor monsters places do { temp = new Rectangle(rand.Next(0, col), rand.Next(0, row), 30, 40); } while(map[temp.X,temp.Y].ocupied); player=new hero(map[temp.X,temp.Y].rect,tree,rand); player_spawn=new Vector2(player.cell.X,player.cell.Y); standing = new Rectangle(10, 150, 30, 40); zombie_standing = new Rectangle(0, 0, 50, 80); frameSize = new int[9]{8,42,75,110,142,173,205,240,275}; attacking_frameSize = new int[7]{ 410,440,480,520,570,630,700}; beaten_frameSize = new int[4] { 195, 222,155, 189 }; deading_frameSize = new int[10] { 195, 222, 155, 189, 375, 406, 335, 370, 455, 495 }; Kamehameha_frameSize = new int[12] { 3, 32, 37, 64, 69, 95, 101, 127, 134, 167, 172, 205 }; zombie_attacking_frameSize = new int[12] {0,50,100,150,200,250,300,350,390,440,480,530 }; zombie_beaten_frameSize = new int[12] {0,50,90,140,190,240,281,332,371,436,480,530 }; zombie_deading_frameSize = new int[12] {672,716,767,820,870,920,967,1013,1064,1110,1160,1210 }; zombie_walking_frameSize = new int[20] {10,60,105,155,208,258,309,359,408,458,509,559,601,654,701,751,804,858,1010,1060}; //zombie_walking_frameSize = new int[12] {10,54,105,155,208,252,309,348,408,457,509,552}; zombie_attack_frameheight=261-184; zombie_beaten_frameheight=347-277; zombie_deading_frameheight=347-277; zombie_walking_frameheight=165-90; deading_frameheight = 373 - 337; beaten_frameheight = 373 - 337; Kamehameha_frameheight = 598 - 561; frameheight = 40; attack_frameheight = 418 - 375; starting_attacking_frame = new Point(410, 375); starting_running_frame = new Point(8, 195); starting_beaten_frame = new Point(195,337); starting_deading_frame = new Point(195, 337); starting_Kamehameha_frame = new Point(3, 561); start_zombie_walking = new Point(10, 90); starting_zombie_attack = new Point(0, 184); starting_zombie_beaten = new Point(0, 277); starting_zombie_deading = new Point(672, 277); running_frame_counter = 0; attacking_frame_counter = 0; beaten_frame_counter = 0; deading_frame_counter = 0; Kamehameha_frame_counter = 0; damage_counter = 0; playerisdead = false; currentKeyboard = new KeyboardState(); oldKeyboard = new KeyboardState(); base.Initialize(); }
/// <summary> /// Adds the token to the chain. /// </summary> public void AddToChain(Token token) { try { // Check to see if there is only one and it is this // one. If it is, then reset the chain. if (chain.Count == 1 && chain.Contains(token)) { chain.Clear(); token.InChain = false; return; } // Check to see if there is anything in the chain already if (chain.Count > 0) { // Go backwards until we find one that is adjacent to // the current one bool addRest = false; bool containsToken = chain.Contains(token); ArrayList <Token> revChain = new ArrayList <Token>(); revChain.AddAll(chain); revChain.Reverse(); LinkedList <Token> newChain = new LinkedList <Token>(); foreach (Token test in revChain) { // Check for containing code if (containsToken && !addRest && test != token) { test.InChain = false; continue; } if (containsToken && test == token) { // Add the rest, but not this one because we // append at the end. addRest = true; continue; } // Check for adjacent if (!addRest && !test.IsAdjacent(token)) { // Pop off this one test.InChain = false; continue; } // Check for adjacent if (test.IsAdjacent(token)) { addRest = true; } // Add the chain test.InChain = true; newChain.Add(test); } // Reverse it again newChain.Reverse(); chain = newChain; } // At this point, we can append the token to the chain chain.Add(token); token.InChain = true; } finally { // Fire a change OnChainChanged(); } }
private void ComputeLogicalNeighbors() { // Determine if any collection in our physical neighbor list is collapsed bool isAnyNeighborCollapsed = false; foreach (LayoutContext neighbor in PhysicalNeighbors) { if (neighbor.DockableCollection.IsCollapsed) { isAnyNeighborCollapsed = true; break; } } if (isAnyNeighborCollapsed) { // At least one neighbor is collapsed. There are two cases // 1. A orthogonal peer of the neighbor will expand to cover the neighbor, in which case we can ignore the neighbor // 2. One or more anticedents will expand, in which case they become logical neighbors. _logicalNeighbors = new LinkedList <LayoutContext>(); foreach (LayoutContext neighbor in PhysicalNeighbors) { if (neighbor.DockableCollection.IsCollapsed) { if (neighbor.Edges[EdgesDockPosition].LogicalReplacements != null) { #if DEBUG // The adjacent and opposing replacement sets should be identical Debug.Assert(neighbor.Edges[LayoutContext.OpposingNeighbors[EdgesDockPosition]].LogicalReplacements != null); LinkedListNode <LayoutContext> adjacentLink = neighbor.Edges[EdgesDockPosition].LogicalReplacements.First; LinkedListNode <LayoutContext> opposingLink = neighbor.Edges[LayoutContext.OpposingNeighbors[EdgesDockPosition]].LogicalReplacements.First; while (adjacentLink != null || opposingLink != null) { Debug.Assert(adjacentLink != null && opposingLink != null); Debug.Assert(adjacentLink.Value == opposingLink.Value); adjacentLink = adjacentLink.Next; opposingLink = opposingLink.Next; } #endif // If we have a replacement that is reachable, that replacement is the neighbor bool foundLogicalNeighbors = false; foreach (LayoutContext replacement in neighbor.Edges[EdgesDockPosition].LogicalReplacements) { if (LayoutContext.IsPhysicallyReachable(replacement, EdgesDockPosition)) { foundLogicalNeighbors = true; if (!_logicalNeighbors.Contains(replacement)) { if (replacement.DockableCollection.IsCollapsed) { throw new InvalidProgramException(); } _logicalNeighbors.AddLast(replacement); } } } // If we found no replacement, then the neighbors are the logical neighbors of the collapsed member if (!foundLogicalNeighbors) { foreach (var logicalNeighbor in neighbor.Edges[EdgesDockPosition].LogicalNeighbors) { if (!_logicalNeighbors.Contains(logicalNeighbor)) { if (logicalNeighbor.DockableCollection.IsCollapsed) { throw new InvalidProgramException(); } _logicalNeighbors.AddLast(logicalNeighbor); } } } } } else if (!_logicalNeighbors.Contains(neighbor)) { _logicalNeighbors.AddLast(neighbor); } } } else { _logicalNeighbors = PhysicalNeighbors; } }
public static void Main() { // <Snippet2> // Create the link list. string[] words = { "the", "fox", "jumps", "over", "the", "dog" }; LinkedList <string> sentence = new LinkedList <string>(words); Display(sentence, "The linked list values:"); Console.WriteLine("sentence.Contains(\"jumps\") = {0}", sentence.Contains("jumps")); // </Snippet2> // Add the word 'today' to the beginning of the linked list. sentence.AddFirst("today"); Display(sentence, "Test 1: Add 'today' to beginning of the list:"); // <Snippet3> // Move the first node to be the last node. LinkedListNode <string> mark1 = sentence.First; sentence.RemoveFirst(); sentence.AddLast(mark1); // </Snippet3> Display(sentence, "Test 2: Move first node to be last node:"); // Change the last node to 'yesterday'. sentence.RemoveLast(); sentence.AddLast("yesterday"); Display(sentence, "Test 3: Change the last node to 'yesterday':"); // <Snippet4> // Move the last node to be the first node. mark1 = sentence.Last; sentence.RemoveLast(); sentence.AddFirst(mark1); // </Snippet4> Display(sentence, "Test 4: Move last node to be first node:"); // <Snippet12> // Indicate the last occurence of 'the'. sentence.RemoveFirst(); LinkedListNode <string> current = sentence.FindLast("the"); // </Snippet12> IndicateNode(current, "Test 5: Indicate last occurence of 'the':"); // <Snippet5> // Add 'lazy' and 'old' after 'the' (the LinkedListNode named current). sentence.AddAfter(current, "old"); sentence.AddAfter(current, "lazy"); // </Snippet5> IndicateNode(current, "Test 6: Add 'lazy' and 'old' after 'the':"); // <Snippet6> // Indicate 'fox' node. current = sentence.Find("fox"); IndicateNode(current, "Test 7: Indicate the 'fox' node:"); // Add 'quick' and 'brown' before 'fox': sentence.AddBefore(current, "quick"); sentence.AddBefore(current, "brown"); // </Snippet6> IndicateNode(current, "Test 8: Add 'quick' and 'brown' before 'fox':"); // Keep a reference to the current node, 'fox', // and to the previous node in the list. Indicate the 'dog' node. mark1 = current; LinkedListNode <string> mark2 = current.Previous; current = sentence.Find("dog"); IndicateNode(current, "Test 9: Indicate the 'dog' node:"); // The AddBefore method throws an InvalidOperationException // if you try to add a node that already belongs to a list. Console.WriteLine("Test 10: Throw exception by adding node (fox) already in the list:"); try { sentence.AddBefore(current, mark1); } catch (InvalidOperationException ex) { Console.WriteLine("Exception message: {0}", ex.Message); } Console.WriteLine(); // <Snippet7> // Remove the node referred to by mark1, and then add it // before the node referred to by current. // Indicate the node referred to by current. sentence.Remove(mark1); sentence.AddBefore(current, mark1); // </Snippet7> IndicateNode(current, "Test 11: Move a referenced node (fox) before the current node (dog):"); // <Snippet8> // Remove the node referred to by current. sentence.Remove(current); // </Snippet8> IndicateNode(current, "Test 12: Remove current node (dog) and attempt to indicate it:"); // Add the node after the node referred to by mark2. sentence.AddAfter(mark2, current); IndicateNode(current, "Test 13: Add node removed in test 11 after a referenced node (brown):"); // The Remove method finds and removes the // first node that that has the specified value. sentence.Remove("old"); Display(sentence, "Test 14: Remove node that has the value 'old':"); // <Snippet9> // When the linked list is cast to ICollection(Of String), // the Add method adds a node to the end of the list. sentence.RemoveLast(); ICollection <string> icoll = sentence; icoll.Add("rhinoceros"); // </Snippet9> Display(sentence, "Test 15: Remove last node, cast to ICollection, and add 'rhinoceros':"); Console.WriteLine("Test 16: Copy the list to an array:"); //<Snippet10> // Create an array with the same number of // elements as the inked list. string[] sArray = new string[sentence.Count]; sentence.CopyTo(sArray, 0); foreach (string s in sArray) { Console.WriteLine(s); } //</Snippet10> //<Snippet11> // Release all the nodes. sentence.Clear(); Console.WriteLine(); Console.WriteLine("Test 17: Clear linked list. Contains 'jumps' = {0}", sentence.Contains("jumps")); //</Snippet11> Console.ReadLine(); }
public bool HasMessage(Api.Message msg) { return(_queue.Contains(msg)); }
public bool isCardInHand(GameObject card) { return(cards.Contains(card)); }
/* * Returns a linked list of the vertices representing the shell of a face list. */ public static LinkedList <int> GetShellVertices(Component component, List <int> floorFaces) { var shellPairs = new List <(int, int)>(); for (int i = 0; i < floorFaces.Count; i++) { Face outerFace = component.GetFace(floorFaces[i]); bool foundPair01 = false; bool foundPair02 = false; bool foundPair12 = false; for (int j = 0; j < floorFaces.Count; j++) { if (i == j) { continue; } Face innerFace = component.GetFace(floorFaces[j]); if (Array.Exists(innerFace.vertexIndices, index => index == outerFace.vertexIndices[0]) && Array.Exists(innerFace.vertexIndices, index => index == outerFace.vertexIndices[1])) { foundPair01 = true; } if (Array.Exists(innerFace.vertexIndices, index => index == outerFace.vertexIndices[0]) && Array.Exists(innerFace.vertexIndices, index => index == outerFace.vertexIndices[2])) { foundPair02 = true; } if (Array.Exists(innerFace.vertexIndices, index => index == outerFace.vertexIndices[1]) && Array.Exists(innerFace.vertexIndices, index => index == outerFace.vertexIndices[2])) { foundPair12 = true; } } if (!foundPair01) { shellPairs.Add((outerFace.vertexIndices[0], outerFace.vertexIndices[1])); } if (!foundPair02) { shellPairs.Add((outerFace.vertexIndices[0], outerFace.vertexIndices[2])); } if (!foundPair12) { shellPairs.Add((outerFace.vertexIndices[1], outerFace.vertexIndices[2])); } } /* Make shellPairs a Linked List */ var linkedList = new LinkedList <int>(); linkedList.AddFirst(shellPairs[0].Item1); linkedList.AddLast(shellPairs[0].Item2); shellPairs.RemoveAt(0); var count = 0; while (shellPairs.Count > 0) { foreach ((int, int)pair in shellPairs) { if (pair.Item1 == linkedList.Last.Value) { if (linkedList.Contains(pair.Item2)) { count++; if (count > 1) { throw new Exception("Shellpair-list is not empty when it should be."); } } else { linkedList.AddLast(pair.Item2); } shellPairs.Remove(pair); break; } else if (pair.Item2 == linkedList.Last.Value) { if (linkedList.Contains(pair.Item1)) { count++; if (count > 1) { throw new Exception("ShellPair-list is not empty when it should be."); } } else { linkedList.AddLast(pair.Item1); } shellPairs.Remove(pair); break; } } } return(linkedList); }
public void TestTransactions() { InitMainNode(); int addressCount = 20; LinkedList <PhantasmaKeys> addressList = new LinkedList <PhantasmaKeys>(); for (int i = 0; i < addressCount; i++) { var key = PhantasmaKeys.Generate(); if (addressList.Contains(key) == false) { addressList.AddLast(key); } } var currentKey = addressList.First; var masterKeys = PhantasmaKeys.FromWIF(nexusWif); //Trace.Message($"Connecting to host: {host} with address {masterKeys.Address.Text}"); var amount = UnitConversion.ToBigInteger(1000000, DomainSettings.StakingTokenDecimals); var hash = SendTransfer(host, masterKeys, currentKey.Value.Address, amount); if (hash == Hash.Null) { return; } ConfirmTransaction(host, hash); int totalTxs = 0; int okTxs = 0; BigInteger currentKeyBalance = GetBalance(currentKey.Value.Address); amount = UnitConversion.ToBigInteger(1000000, DomainSettings.FuelTokenDecimals); SendTransfer(host, masterKeys, currentKey.Value.Address, amount, "KCAL"); //while (currentKeyBalance > 9999) while (totalTxs < 10) { var destKey = currentKey.Next != null ? currentKey.Next : addressList.First; var txHash = SendTransfer(host, currentKey.Value, destKey.Value.Address, currentKeyBalance - 9999); if (txHash == Hash.Null) { amount = UnitConversion.ToBigInteger(1000000, DomainSettings.FuelTokenDecimals); SendTransfer(host, masterKeys, currentKey.Value.Address, amount); } do { Thread.Sleep(100); } while (!mempool.IsEmpty()); var confirmation = ConfirmTransaction(host, hash); okTxs += confirmation ? 1 : 0; totalTxs++; currentKey = destKey; currentKeyBalance = GetBalance(currentKey.Value.Address); Trace.WriteLine(currentKeyBalance); } Assert.IsTrue(okTxs == totalTxs); CloseNode(); }
void MoveToPosition(Vector3 target) { if (!readyForClick) { if (clickedFloors.Count != 0) { if (Mathf.Abs(transform.position.y - Floor3.transform.position.y) < 0.01 && floorsToVisit.Contains(Floor3)) { readyForClick = true; floorsToVisit.Remove(Floor3); if (pressedButtons.Contains(Button3U)) { pressedButtons.Find(Button3U).Value.GetComponent <SpriteRenderer>().color = Color.red; pressedButtons.Remove(Button3U); } else { pressedButtons.Find(Button3D).Value.GetComponent <SpriteRenderer>().color = Color.red; pressedButtons.Remove(Button3D); } } if (Mathf.Abs(transform.position.y - Floor2.transform.position.y) < 0.01 && floorsToVisit.Contains(Floor2)) { readyForClick = true; floorsToVisit.Remove(Floor2); if (pressedButtons.Contains(Button2U)) { pressedButtons.Find(Button2U).Value.GetComponent <SpriteRenderer>().color = Color.red; pressedButtons.Remove(Button2U); } else { pressedButtons.Find(Button2D).Value.GetComponent <SpriteRenderer>().color = Color.red; pressedButtons.Remove(Button2D); } } if (Mathf.Abs(transform.position.y - Floor1.transform.position.y) < 0.01 && floorsToVisit.Contains(Floor1)) { readyForClick = true; floorsToVisit.Remove(Floor1); pressedButtons.Find(Button1U).Value.GetComponent <SpriteRenderer>().color = Color.red; pressedButtons.Remove(Button1U); } if (Mathf.Abs(transform.position.y - Floor4.transform.position.y) < 0.01 && floorsToVisit.Contains(Floor4)) { readyForClick = true; floorsToVisit.Remove(Floor4); pressedButtons.Find(Button4D).Value.GetComponent <SpriteRenderer>().color = Color.red; pressedButtons.Remove(Button4D); } } transform.position = Vector3.MoveTowards(transform.position, target, Time.deltaTime * .5f); } }
public bool Contains(T value) { return(m_UnderLyingLinkedList.Contains(value)); }
public void EjectProduct(Product product, LinkedList<Product> productCase) { Contract.Requires(CheckAvailability(product), "PRE: Sought item must be in stock"); Contract.Requires(Stock != null); Contract.Requires(productCase != null); Contract.Requires(product != null); Contract.Ensures(productCase.Contains(product), "POST: Sought item must be ejected"); Contract.Ensures(Contract.OldValue((int)Stock.Where(el => (string)el.Element("Name") == product.Name).Single().Element("Ammount")) - 1 == (int)Stock.Where(el => (string)el.Element("Name") == product.Name).Single().Element("Ammount")); XElement node = Stock.Where(el => (string)el.Element("Name") == product.Name).Single(); node.Element("Ammount").Value = ((int)node.Element("Ammount") - 1).ToString(); productCase.AddLast(new Product(product.Name,1,product.Price)); Database.Save("StockDatabase.xml"); }
public override void PageSearch(LinkedList llstCondition) { _chartVariable = new ChartInterface(); this._llstSearchCondition.Clear(); if (!llstCondition.Contains(Definition.DynamicCondition_Search_key.AREA)) { MSGHandler.DisplayMessage(MSGType.Information, MSGHandler.GetMessage(Definition.MSG_KEY_SELECT_CONDITION_DATA)); return; } DataTable dt = null; if (llstCondition[Definition.DynamicCondition_Search_key.FROMDATE] != null) { dt = (DataTable)llstCondition[Definition.DynamicCondition_Search_key.FROMDATE]; DateTime dtFrom = (DateTime)dt.Rows[0][Definition.DynamicCondition_Condition_key.DATETIME_VALUEDATA]; sStartTime = CommonPageUtil.StartDate(dtFrom.ToString(Definition.DATETIME_FORMAT)); } if (llstCondition[Definition.DynamicCondition_Search_key.TODATE] != null) { dt = (DataTable)llstCondition[Definition.DynamicCondition_Search_key.TODATE]; DateTime dtTo = (DateTime)dt.Rows[0][Definition.DynamicCondition_Condition_key.DATETIME_VALUEDATA]; sEndTime = CommonPageUtil.EndDate(dtTo.ToString(Definition.DATETIME_FORMAT)); } this._llstSearchCondition.Add(Definition.DynamicCondition_Condition_key.START_DTTS, sStartTime); this._llstSearchCondition.Add(Definition.DynamicCondition_Condition_key.END_DTTS, sEndTime); if (llstCondition[Definition.DynamicCondition_Search_key.LINE] != null) { dt = (DataTable)llstCondition[Definition.DynamicCondition_Search_key.LINE]; _line = dt.Rows[0][Definition.DynamicCondition_Condition_key.DISPLAYDATA].ToString(); _chartVariable.LINE = _line; this._llstSearchCondition.Add(Definition.DynamicCondition_Condition_key.LINE_RAWID, dt.Rows[0][Definition.DynamicCondition_Condition_key.VALUEDATA].ToString()); } string strArea = _ComUtil.GetConditionString((DataTable)llstCondition[Definition.DynamicCondition_Search_key.AREA], Definition.DynamicCondition_Condition_key.AREA); if (!string.IsNullOrEmpty(strArea)) { this._llstSearchCondition.Add(Definition.DynamicCondition_Condition_key.AREA, strArea); } string strParamType = _ComUtil.GetConditionData((DataTable)llstCondition[Definition.DynamicCondition_Search_key.PARAM_TYPE], Definition.DynamicCondition_Condition_key.VALUEDATA); if (!string.IsNullOrEmpty(strParamType)) { this._llstSearchCondition.Add(Definition.DynamicCondition_Condition_key.PARAM_TYPE_CD, strParamType); } if (!llstCondition.Contains(Definition.DynamicCondition_Search_key.SPC_MODEL_CONFIG_RAWID)) { MSGHandler.DisplayMessage(MSGType.Information, "Please Select SPC Model."); return; } string strModelConfigRawID = ((DataTable)llstCondition[Definition.DynamicCondition_Search_key.SPC_MODEL_CONFIG_RAWID]).Rows[0][Definition.DynamicCondition_Condition_key.VALUEDATA].ToString(); if (!string.IsNullOrEmpty(strModelConfigRawID)) { this._llstSearchCondition.Add(Definition.DynamicCondition_Condition_key.MODEL_CONFIG_RAWID, strModelConfigRawID); } PROC_DataBinding(); }
/// <summary> /// Updates the collisionmap, adding the rectangle to the collisionmap, and performing new connections, as for placing nodes /// </summary> /// <param name="rect"></param> public BuildingMesh PlaceBuilding(Rectangle rect) { CollisionChangedEvent e = new CollisionChangedEvent(); e.collision = this; e.changedRect = rect; e.collisionAdded = true; long ticks = DateTime.UtcNow.Ticks; e.oldData = (Boolean[])data.Clone(); Console.Out.WriteLine("Clone time: " + (DateTime.UtcNow.Ticks - ticks) / 10000 + "ms"); ticks = DateTime.UtcNow.Ticks; Boolean color = true; // Update collisionmap data for (int i = rect.Left; i < rect.Right; i++) { for (int j = rect.Top; j < rect.Bottom; j++) { data[PointToIndex(i, j)] = color; } } // Update collisionmap texture this.texture = BoolToTexture(Game1.GetInstance().graphics.GraphicsDevice, this.data, mapWidth, collisionMapTextureScale); e.newData = data; Console.Out.WriteLine("Data put time: " + (DateTime.UtcNow.Ticks - ticks) / 10000 + "ms"); ticks = DateTime.UtcNow.Ticks; Node[] newNodes = new Node[4]; RTSCollisionMap map = Game1.GetInstance().collision; newNodes[0] = new Node(map, rect.Left - 1, rect.Top - 1, true); newNodes[1] = new Node(map, rect.Right + 1, rect.Top - 1, true); newNodes[2] = new Node(map, rect.Left - 1, rect.Bottom + 1, true); newNodes[3] = new Node(map, rect.Right + 1, rect.Bottom + 1, true); Console.Out.WriteLine("Node create time: " + (DateTime.UtcNow.Ticks - ticks) / 10000 + "ms"); ticks = DateTime.UtcNow.Ticks; BuildingMesh mesh = new BuildingMesh(this); mesh.rect = rect; mesh.createdNodes = newNodes; LinkedList<PathfindingNode> nodes = PathfindingNodeManager.GetInstance().nodeList; foreach (PathfindingNode node in nodes) { if (rect.Contains(node.GetLocation())) mesh.removedNodes.AddLast(node.GetLocation()); } Console.Out.WriteLine("Mesh create time: " + (DateTime.UtcNow.Ticks - ticks) / 10000 + "ms"); ticks = DateTime.UtcNow.Ticks; LinkedList<Node> processedNodes = new LinkedList<Node>(); int nodesAdded = 0; foreach (Node newNode in newNodes) { foreach (Node connectedNode in newNode.GetConnectedNodes()) { // Let's not process things twice, as it's quite a heavy computation if (!processedNodes.Contains(connectedNode)) { // Remove its current nodes connectedNode.RemoveAllConnections(); // Scedule it for reprocessing SmartPathfindingNodeProcessor.GetInstance().Push(connectedNode); processedNodes.AddLast(connectedNode); nodesAdded++; } } } Console.Out.WriteLine("Node connection time: " + (DateTime.UtcNow.Ticks - ticks) / 10000 + "ms, adding " + nodesAdded + " nodes"); ticks = DateTime.UtcNow.Ticks; FireCollisionChangedEvent(e); Console.Out.WriteLine("Event time: " + (DateTime.UtcNow.Ticks - ticks)); return mesh; }
public void Algorithm_OPT() { LinkedList <int> q = new LinkedList <int>(); int queyecishu = 0; int time = 0; int b = 0; int wulikuai = Request.NumsOfwulikuai; for (int i = 0; i <= list.Count; i++) { bool queye = true; if (i != 0) { String a = Convert.ToString(list[i - 1]); b = Convert.ToInt32(a); if (q.Contains(b)) { queye = false; } else//不包含,那么需要有页面出来 { queyecishu++; if (q.Count == wulikuai) { int[] nums = q.ToArray(); q.Remove(DeleteOpt(i - 1, nums)); } q.AddFirst(b); } } for (int j = 0; j < wulikuai + 3; j++) { Label lab = new Label(); if (i == 0) { lab = StyleLable(lab, 1, i, j); if (j == 0) { lab.Text = "访问序列"; MyPanel.Invoke(new Action(() => { MyPanel.Controls.Add(lab); } )); } else if (j <= wulikuai) { lab.Text = "物理块" + j.ToString(); MyPanel.Invoke(new Action(() => { MyPanel.Controls.Add(lab); } )); } else { if (j == wulikuai + 1) { lab.Text = "是否缺页"; MyPanel.Invoke(new Action(() => { MyPanel.Controls.Add(lab); } )); } else { lab.Text = "缺页率"; MyPanel.Invoke(new Action(() => { MyPanel.Controls.Add(lab); } )); } } } else { lab = StyleLable(lab, 2, i, j); int[] num = q.ToArray(); if (j == 0) { lab.Text = Convert.ToString(list[i - 1]); } else if (j <= wulikuai) { if (j <= q.Count) { if (queye && b == num[j - 1]) { lab.ForeColor = Color.Red; } lab.Text = num[j - 1].ToString(); } } else { if (j == wulikuai + 1) { if (queye) { lab.Text = "√"; } } else//缺页率的计算 { double jieguo = (double)queyecishu / (double)(i) * 100; lab.Text = ((double)(double)queyecishu / (double)(i) * 100).ToString(); Request.test_OPT.Add(jieguo); } } if (MyPanel.IsHandleCreated) { MyPanel.Invoke(new Action(() => { MyPanel.AutoScrollPosition = new Point(0, 0); MyPanel.Controls.Add(lab); } )); } } } MyPanel.Invoke(new Action(() => { time = FlashTime("OPT算法时间 ", queye, time); } )); Sleep(TimeSpan.FromSeconds(1)); } }
public Boolean Contains(T item) { return(items.Contains(item)); }
/// <summary>Overload</summary> public bool ContainTop(Point p) => _setOfTops.Contains(p);
/// <summary> /// TBD /// </summary> /// <param name="message">TBD</param> /// <exception cref="ArgumentException"> /// This exception is thrown when the <see cref="Mode"/> is set to <see cref="ReplayFilterMode.Disabled"/>. /// </exception> /// <exception cref="IllegalStateException"> /// This exception is thrown when either the replayed event is in the wrong order or from an old writer. /// </exception> /// <returns>TBD</returns> protected override bool Receive(object message) { if (message is ReplayedMessage) { var r = (ReplayedMessage)message; if (DebugEnabled && _log.IsDebugEnabled) { _log.Debug($"Replay: {r.Persistent}"); } try { if (_buffer.Count == WindowSize) { var msg = _buffer.First; _buffer.RemoveFirst(); PersistentActor.Tell(msg.Value, ActorRefs.NoSender); } if (r.Persistent.WriterGuid.Equals(_writerUuid)) { // from same writer if (r.Persistent.SequenceNr < _sequenceNr) { var errMsg = $@"Invalid replayed event [sequenceNr={r.Persistent.SequenceNr}, writerUUID={r.Persistent.WriterGuid}] as the sequenceNr should be equal to or greater than already-processed event [sequenceNr={_sequenceNr}, writerUUID={_writerUuid}] from the same writer, for the same persistenceId [{r.Persistent.PersistenceId}]. Perhaps, events were journaled out of sequence, or duplicate PersistentId for different entities?"; LogIssue(errMsg); switch (Mode) { case ReplayFilterMode.RepairByDiscardOld: //discard break; case ReplayFilterMode.Fail: throw new IllegalStateException(errMsg); case ReplayFilterMode.Warn: _buffer.AddLast(r); break; case ReplayFilterMode.Disabled: throw new ArgumentException("Mode must not be Disabled"); } } else { // note that it is alright with == _sequenceNr, since such may be emitted by EventSeq _buffer.AddLast(r); _sequenceNr = r.Persistent.SequenceNr; } } else if (_oldWriters.Contains(r.Persistent.WriterGuid)) { // from old writer var errMsg = $@"Invalid replayed event [sequenceNr={r.Persistent.SequenceNr}, writerUUID={r.Persistent.WriterGuid}]. There was already a newer writer whose last replayed event was [sequenceNr={_sequenceNr}, writerUUID={_writerUuid}] for the same persistenceId [{r.Persistent.PersistenceId}]. Perhaps, the old writer kept journaling messages after the new writer created, or duplicate PersistentId for different entities?"; LogIssue(errMsg); switch (Mode) { case ReplayFilterMode.RepairByDiscardOld: //discard break; case ReplayFilterMode.Fail: throw new IllegalStateException(errMsg); case ReplayFilterMode.Warn: _buffer.AddLast(r); break; case ReplayFilterMode.Disabled: throw new ArgumentException("Mode must not be Disabled"); } } else { // from new writer if (!string.IsNullOrEmpty(_writerUuid)) { _oldWriters.AddLast(_writerUuid); } if (_oldWriters.Count > MaxOldWriters) { _oldWriters.RemoveFirst(); } _writerUuid = r.Persistent.WriterGuid; _sequenceNr = r.Persistent.SequenceNr; // clear the buffer from messages from other writers with higher SequenceNr var node = _buffer.First; while (node != null) { var next = node.Next; var msg = node.Value; if (msg.Persistent.SequenceNr >= _sequenceNr) { var errMsg = $@"Invalid replayed event [sequenceNr=${r.Persistent.SequenceNr}, writerUUID=${r.Persistent.WriterGuid}] from a new writer. An older writer already sent an event [sequenceNr=${msg.Persistent.SequenceNr}, writerUUID=${msg.Persistent.WriterGuid}] whose sequence number was equal or greater for the same persistenceId [${r.Persistent.PersistenceId}]. Perhaps, the new writer journaled the event out of sequence, or duplicate PersistentId for different entities?"; LogIssue(errMsg); switch (Mode) { case ReplayFilterMode.RepairByDiscardOld: _buffer.Remove(node); //discard break; case ReplayFilterMode.Fail: throw new IllegalStateException(errMsg); case ReplayFilterMode.Warn: // keep break; case ReplayFilterMode.Disabled: throw new ArgumentException("Mode must not be Disabled"); } } node = next; } _buffer.AddLast(r); } } catch (IllegalStateException ex) { if (Mode == ReplayFilterMode.Fail) { Fail(ex); } else { throw; } } } else if (message is RecoverySuccess || message is ReplayMessagesFailure) { if (DebugEnabled) { _log.Debug($"Replay completed: {message}"); } SendBuffered(); PersistentActor.Tell(message, ActorRefs.NoSender); Context.Stop(Self); } else { return(false); } return(true); }
public bool ContainsKey(ReportSpec reportSpec) { return(_dictionary.ContainsKey(reportSpec) && _list.Contains(reportSpec)); }
/// <summary> /// 艦娘図鑑から回避・対潜の初期値及び説明文を読み込みます。 /// </summary> private void AlbumOpened( string apiname, dynamic data ) { if ( data == null || !data.api_list() ) //空のページ return; foreach ( dynamic elem in data.api_list ) { if ( !elem.api_yomi() ) break; //装備図鑑だった場合終了 int shipID = (int)elem.api_table_id[0]; var ship = KCDatabase.Instance.MasterShips[shipID]; ShipParameterElement e = this[shipID]; if ( e == null ) { e = new ShipParameterElement(); e.ShipID = shipID; Utility.Logger.Add( 2, ship.NameWithClass + LoggerRes.RegisteredParameters ); } if ( e.ASW.SetEstParameter( 1, (int)elem.api_tais, Parameter.MaximumDefault ) ) Utility.Logger.Add( 1, string.Format( "ShipParameter: {0} の対潜値が予測範囲から外れました( [{1} ~ {2}] ~ {3} )。", ship.NameWithClass, e.ASW.MinimumEstMin, e.ASW.MinimumEstMax, e.ASW.Maximum ) ); if ( e.Evasion.SetEstParameter( 1, (int)elem.api_kaih, Parameter.MaximumDefault ) ) Utility.Logger.Add( 1, string.Format( "ShipParameter: {0} の回避値が予測範囲から外れました( [{1} ~ {2}] ~ {3} )。", ship.NameWithClass, e.Evasion.MinimumEstMin, e.Evasion.MinimumEstMax, e.Evasion.Maximum ) ); { //図鑑説明文登録(図鑑に載っていない改装艦に関してはその改装前の艦の説明文を設定する) e.MessageAlbum = elem.api_sinfo; LinkedList<int> processedIDs = new LinkedList<int>(); while ( ship != null && !processedIDs.Contains( ship.ShipID ) && ship.RemodelAfterShipID > 0 ) { processedIDs.AddLast( ship.ID ); ShipParameterElement e2 = this[ship.RemodelAfterShipID]; if ( e2 == null ) { e2 = new ShipParameterElement(); e2.ShipID = ship.RemodelAfterShipID; } if ( e2.MessageAlbum == null ) { e2.MessageAlbum = e.MessageAlbum; Update( e2 ); } ship = KCDatabase.Instance.MasterShips[ship.RemodelAfterShipID]; } } Update( e ); //Utility.Logger.Add( 1, KCDatabase.Instance.MasterShips[shipID].NameWithClass + "のパラメータを更新しました。" ); } }
/// <summary> /// Determines whether the cache contains the key. /// </summary> /// <param name="key">The key.</param> /// <returns> /// <c>true</c> if the specified key contains key; otherwise, <c>false</c>. /// </returns> public override bool ContainsKey(object key) { return(keyList.Contains(key)); }
public void TestRemoveValue() { var list = new LinkedList<string>(); list.AddLast("Expected"); list.AddLast("Expected"); list.AddLast("Not expected"); list.AddLast("Expected"); Assert.IsTrue(list.Remove("Not expected")); Assert.IsFalse(list.Contains("Not expected")); }
// Get a random Noble bunny from surrounding of a White Walker bunny. private static Bunny GetANobleBunnyFromSurrounding(int whiteX, int whiteY, Bunny[,] bunniesGrid, LinkedList <Bunny> infectedNobleBunnies) { // Creating a list of Noble bunnies in surrounding of a White Walker bunny. LinkedList <Bunny> nobleBunnies = new LinkedList <Bunny>(); // Determining the range for searching, to prevent edge cases (out if index). int minXRange, maxXRange, minYRange, maxYRange; // X axis range. if (whiteX == 0) { minXRange = 0; maxXRange = 2; } else if (whiteX == bunniesGrid.GetLength(0) - 1) { minXRange = bunniesGrid.GetLength(0) - 2; maxXRange = bunniesGrid.GetLength(0); } else { minXRange = whiteX - 1; maxXRange = whiteX + 2; } // Y axis range. if (whiteY == 0) { minYRange = 0; maxYRange = 2; } else if (whiteY == bunniesGrid.GetLength(1) - 1) { minYRange = bunniesGrid.GetLength(1) - 2; maxYRange = bunniesGrid.GetLength(1); } else { minYRange = whiteY - 1; maxYRange = whiteY + 2; } // Start searching for noble bunnies in compliance with range boundaries. for (int x = minXRange; x < maxXRange; x++) { for (int y = minYRange; y < maxYRange; y++) { /* Check to prevent empty spaces, White Walker bunnies and already chosen Noble bunnies to be infected. * (A Noble bunny can be selected for infection by only one White Walker bunny). */ if (bunniesGrid[x, y] != null && bunniesGrid[x, y].house != "White Walker" && !infectedNobleBunnies.Contains(bunniesGrid[x, y])) { nobleBunnies.AddLast(bunniesGrid[x, y]); } } } // Get a random Noble bunny from the found Noble bunnies and return it. if (nobleBunnies.Count > 0) { return(GetARandomBunny(nobleBunnies)); } return(null); }
private static void ExecuteCommand(LinkedList<int> numbers, int numOne, int numTwo, string command) { if (numbers.Count == 0) { numbers.AddLast(numTwo); } if (!numbers.Contains(numTwo)) { bool isAdded = false; for (int i = 0; i < numbers.Count; i++) { var temp = numbers.ElementAt(i); if (temp > numTwo) { LinkedListNode<int> node = numbers.Find(temp); numbers.AddBefore(node, numTwo); isAdded = true; break; } } if (!isAdded) { numbers.AddLast(numTwo); } } if (numbers.Contains(numOne)) { return; } LinkedListNode<int> current = numbers.Find(numTwo); if (command == "before") { bool isAdded = false; for (int i = 0; i < numbers.IndexOf(numTwo); i++) { var temp = numbers.ElementAt(i); if (temp > numOne) { LinkedListNode<int> node = numbers.Find(temp); numbers.AddBefore(node, numOne); isAdded = true; break; } } if (!isAdded) { numbers.AddBefore(current, numOne); } } else { bool isAdded = false; for (int i = numbers.IndexOf(numTwo) + 1; i < numbers.Count - 1; i++) { var temp = numbers.ElementAt(i); if (temp > numOne) { LinkedListNode<int> node = numbers.Find(temp); numbers.AddBefore(node, numOne); isAdded = true; break; } } if (!isAdded) { numbers.AddLast(numOne); } } }
public void ContainsIsFalseDefault() { var target = new LinkedList<int>(); Assert.IsFalse(target.Contains(1)); }
internal void ResetSentinel() { if (ResetSentinelFlag != 0) { return; } if (Interlocked.Increment(ref ResetSentinelFlag) != 1) { Interlocked.Decrement(ref ResetSentinelFlag); return; } string masterhostEnd = _masterHost; var allkeys = _ib.GetKeys().ToList(); for (int i = 0; i < _sentinels.Count; i++) { if (i > 0) { var first = _sentinels.First; _sentinels.RemoveFirst(); _sentinels.AddLast(first.Value); } try { using (var sentinelcli = new RedisSentinelClient(_sentinels.First.Value)) { var masterhost = sentinelcli.GetMasterAddrByName(_connectionString.Host); var masterConnectionString = localTestHost(masterhost, RoleType.Master); if (masterConnectionString == null) { continue; } masterhostEnd = masterhost; if (_rw_splitting) { foreach (var slave in sentinelcli.Salves(_connectionString.Host)) { ConnectionStringBuilder slaveConnectionString = localTestHost($"{slave.ip}:{slave.port}", RoleType.Slave); if (slaveConnectionString == null) { continue; } } } foreach (var sentinel in sentinelcli.Sentinels(_connectionString.Host)) { var remoteSentinelHost = $"{sentinel.ip}:{sentinel.port}"; if (_sentinels.Contains(remoteSentinelHost)) { continue; } _sentinels.AddLast(remoteSentinelHost); } } break; } catch { } } foreach (var spkey in allkeys) { _ib.TryRemove(spkey, true); } Interlocked.Exchange(ref _masterHost, masterhostEnd); Interlocked.Decrement(ref ResetSentinelFlag); ConnectionStringBuilder localTestHost(string host, RoleType role) { ConnectionStringBuilder connectionString = _connectionString.ToString(); connectionString.Host = host; connectionString.MinPoolSize = 1; connectionString.MaxPoolSize = 1; using (var cli = new RedisClient(connectionString)) { if (cli.Role().role != role) { return(null); } if (role == RoleType.Master) { //test set/get } } connectionString.MinPoolSize = _connectionString.MinPoolSize; connectionString.MaxPoolSize = _connectionString.MaxPoolSize; _ib.TryRegister(host, () => new RedisClientPool(connectionString, null, TopOwner)); allkeys.Remove(host); return(connectionString); } }
/// <summary> /// Checks if a specified key is pressed. /// </summary> /// <param name="key">Key</param> /// <returns>true if the key is pressed; otherwise, false</returns> public static bool IsKeyDown(Key key) => Keys.Contains(key);
public override void RefreshCondition(LinkedList ll) { if (ll == null) { return; } if (ll.Contains(Definition.DynamicCondition_Search_key.CHART_ID)) { DataTable dtChartID = (DataTable)ll[Definition.DynamicCondition_Search_key.CHART_ID]; string value = DCUtil.GetValueData(dtChartID); this.btxt_ChartID.Text = value; } if (ll.Contains(Definition.CONDITION_SEARCH_KEY_EQP)) { DataTable dtEQPID = (DataTable)ll[Definition.CONDITION_SEARCH_KEY_EQP]; string value = DCUtil.GetValueData(dtEQPID); this.btxt_EQPID.Text = value; } if (ll.Contains(Definition.CONDITION_SEARCH_KEY_MODULE)) { DataTable dtModuleID = (DataTable)ll[Definition.CONDITION_SEARCH_KEY_MODULE]; string value = DCUtil.GetValueData(dtModuleID); this.btxt_ModuleID.Text = value; } if (ll.Contains(Definition.CONDITION_SEARCH_KEY_LOT)) { DataTable dtLot = (DataTable)ll[Definition.CONDITION_SEARCH_KEY_LOT]; string value = DCUtil.GetValueData(dtLot); this.btxt_LotID.Text = value; } if (ll.Contains(Definition.CONDITION_SEARCH_KEY_SUBSTRATE)) { DataTable dtSubstrate = (DataTable)ll[Definition.CONDITION_SEARCH_KEY_SUBSTRATE]; string value = DCUtil.GetValueData(dtSubstrate); this.btxt_SubstrateID.Text = value; } if (ll.Contains(Definition.CONDITION_SEARCH_KEY_RECIPE)) { DataTable dtRecipe = (DataTable)ll[Definition.CONDITION_SEARCH_KEY_RECIPE]; string value = DCUtil.GetValueData(dtRecipe); this.btxt_RecipeID.Text = value; } if (ll.Contains(Definition.CONDITION_SEARCH_KEY_OCAP_OOC)) { DataTable dtOCAPOOC = (DataTable)ll[Definition.CONDITION_SEARCH_KEY_OCAP_OOC]; string value = DCUtil.GetValueData(dtOCAPOOC); if (value == "OCAP") { this.brbtn_OCAP.Checked = true; this.brbtn_OOC.Checked = false; } else { this.brbtn_OCAP.Checked = false; this.brbtn_OOC.Checked = true; } } }
public LinkedList<ImpactItem> GetAllLinks() { LinkedList<ImpactItem> mergedList = new LinkedList<ImpactItem>(); foreach (ImpactItem ii in needsUpdateLinks) { if (!mergedList.Contains(ii)) { mergedList.AddLast(ii); } } foreach (ImpactItem ii in impactedHWLinks) { if (!mergedList.Contains(ii)) { mergedList.AddLast(ii); } } foreach (ImpactItem ii in specifiedByLinks) { if (!mergedList.Contains(ii)) { mergedList.AddLast(ii); } } foreach (ImpactItem ii in verifiedByLinks) { if (!mergedList.Contains(ii)) { mergedList.AddLast(ii); } } foreach (ImpactItem ii in unspecifiedLinks) { if (!mergedList.Contains(ii)) { mergedList.AddLast(ii); } } return mergedList; }
static void UnitTest_07() { LinkedList <EUIPanelID> ll = new LinkedList <EUIPanelID>(); bool b = ll.Contains(EUIPanelID.INT1); }
public static void Show() { { // Array 类型 { //Array: 在内存上连续分配,且元素类型一致 //可以访问坐标 读取快--增删慢 长度不变 Console.WriteLine("************Array**********"); int[] intArray = new int[3]; intArray[0] = 1; string[] strings = new string[] { "123", "234" }; } { // ArrayList 不定长, 连续分配的 // 元素没有类型限制,任何元素都是当成object 处理, 如果是值类型,会有装箱操作 // 可以访问坐标 读取快--增删慢 Console.WriteLine("*******************Array List****************"); ArrayList arrayList = new ArrayList(); arrayList.Add("Ivan"); arrayList.Add("Is"); arrayList.Add(32); //arrayList[4] = 26; //索引赋值 不会增加长度,会报错因为空间不足 } { //List: 也是Array 内存上都是连续摆放的,可以以索引方式访问 // 不定长; 泛型, 保证类型安全,避免装箱拆箱 // 可以访问坐标 读取快--增删慢 Console.WriteLine("*********************List ***********************"); List <int> intList = new List <int>() { 1, 2, 3, 4 }; List <string> strList = new List <string>(); //strList[0] = "1"; // 异常,原因同上 } } { // 链表 { //LinkedList: 泛型特点; 链表 元素不连续分配,每个元素都有记录前后节点 // 找元素只能遍历 查找不方便 // 增删 比较方便 Console.WriteLine("********************************Linked List**************************"); LinkedList <int> linkedList = new LinkedList <int>(); linkedList.AddFirst(123); linkedList.AddLast(234); var isContain = linkedList.Contains(123); LinkedListNode <int> node123 = linkedList.Find(123); if (node123 == null) { return; } linkedList.AddBefore(node123, 0); linkedList.AddAfter(node123, 9); linkedList.Remove(234); linkedList.Remove(node123); linkedList.RemoveFirst(); linkedList.RemoveLast(); } { //Queue: 就是链表 先进先出 放任务 延迟执行, A 不断写入日子任务 B 不断获取任务去执行 Console.WriteLine("******************Queue*********************"); Queue <string> nums = new Queue <string>(); nums.Enqueue("one"); nums.Enqueue("two"); nums.Enqueue("three"); } { // Stack 也是链表 先进后出 解析表达目录树的时候 先产生的数据后使用 Console.WriteLine("*************************Stack**********************"); Stack <string> stack = new Stack <string>(); stack.Push("one"); stack.Push("Two"); stack.Push("Three"); stack.Push("Four"); stack.Push("Five"); } } { //SET 集合 { //HashSet: hash分布, 元素间没有关系,动态增加容量,可以去重 //统计用户 IP 交差并补 -- 二次好友/间接关注/共同好友/粉丝合集 Console.WriteLine("*******************HashSet********************"); HashSet <string> hash = new HashSet <string>(); hash.Add("123"); hash.Add("456"); hash.Add("789"); hash.Add("987"); hash.Add("765"); hash.Add("543"); hash.Add("321"); hash.Add("321"); hash.Add("321"); hash.Add("321"); { HashSet <string> hash1 = new HashSet <string>(); hash1.Add("123"); hash1.Add("789"); hash1.Add("111"); hash1.SymmetricExceptWith(hash); // 补 hash1.UnionWith(hash); // 并 hash1.ExceptWith(hash); // 差 hash1.IntersectWith(hash); // 交 } } { //排序集合 去重且排序 // 统计排名 -- 每统计一个就丢进去集合 Console.WriteLine("*********************SortedList*******************"); SortedSet <string> sortedSet = new SortedSet <string>(); sortedSet.Add("123"); sortedSet.Add("456"); sortedSet.Add("789"); sortedSet.Add("987"); sortedSet.Add("765"); sortedSet.Add("543"); sortedSet.Add("321"); sortedSet.Add("321"); sortedSet.Add("321"); sortedSet.Add("321"); } } { // HashTable key-value 不定长 拿着key计算一个地址,然后放入key-value // object - 装箱拆箱 如果不同的key得到相同的地址,第二个在前面地址+1 // 查找的时候,如果地址对应数据的key不对,那就+1 查找 // 浪费空间,hashtable是基于数组实现的 // 查找数据 一次定位;增删 一次定位 增删改查都很快 // 数据太多,重复定位,效率就下去了。 { Console.WriteLine("*************************Hash Table***************************"); Hashtable table = new Hashtable(); table.Add("123", "456"); table[234] = 456; table["ivan"] = 456; Hashtable.Synchronized(table);// 线程安全 } { //字典 泛型 key-value 增删改查都很快,有序 Console.WriteLine("********************************Dictionary***************************"); Dictionary <int, string> dic = new Dictionary <int, string>(); dic.Add(1, "haha"); } { Console.WriteLine("******************Sorted Dictionary*********************"); SortedDictionary <int, string> dic = new SortedDictionary <int, string>(); dic.Add(1, "Ivan"); dic.Add(3, "Ivan1"); dic.Add(2, "Ivan2"); } { Console.WriteLine("***************Sort List*******************"); SortedList sortedList = new SortedList(); sortedList.Add("First", "Hello"); sortedList.Add("Second", "Hello"); //sortedList.Add("Second", "Hello"); // 不能重复key } { List <string> fruit = new List <string>() { "apple", "apple", "apple", "apple", "apple", "apple", "apple" }; IEnumerable <string> query = fruit.Where(fruit => fruit.Length > 6); // where 中是传入的委托 foreach (var item in query) // 遍历才会去查询比较 迭代器 yield { } IQueryable <string> queryable = fruit.AsQueryable <string>().Where(s => s.Length > 5); // where 中传入的是表达式目录树 foreach (var item in queryable) // 表达式目录树的解析, 延迟到遍历时候才去执行, EF的延迟查询 { } } } }
public static bool Contains <TSource>(this LinkedList <TSource> source, TSource value) => source.Contains(value);
/// <inheritdoc /> /// <example> /// <code source="..\..\NGenerics.Examples\DataStructures\Queues\CircularQueueExamples.cs" region="Contains" lang="cs" title="The following example shows how to use the Contains method."/> /// </example> public bool Contains(T item) { return(_data.Contains(item)); }
/// <summary> /// Returns whether or not the directory contains the specified entry. /// </summary> /// <param name="entry"></param> /// <returns></returns> public bool Contains(VirtualFileSystemEntry entry) { return(mEntries.Contains(entry)); }
public bool Contains(T item) { return(m_List.Contains(item)); }
/// <summary> /// Recursive function to find impact starting from a specific TC. /// </summary> /// <param name="impactList"></param> /// <param name="level"></param> /// <param name="startSimilarity"></param> /// <returns></returns> public LinkedList<ImpactItem> FindImpact(LinkedList<ImpactItem> impactList, double level, double startSimilarity) { if (Visited) { return impactList; } else { Visited = true; } if (level > MAX_LEVELS_FOLLOW) { return impactList; } // Deal with the current TrackerCase LinkedList<ImpactItem> tmpList = GetAllLinks(); foreach (ImpactItem tmp in tmpList) { if (tmp.LevelsFromSource == -1) { tmp.LevelsFromSource = level; } else if (tmp.LevelsFromSource > level) { tmp.LevelsFromSource = level; } if (impactList.Contains(tmp)) { tmp.RankingValue += (ALPHA * tmp.Centrality + (1 - ALPHA) * startSimilarity) / (1 + level * LEVEL_PENELTY); tmp.NbrInLinks++; } else { tmp.RankingValue = (ALPHA * tmp.Centrality + (1 - ALPHA) * startSimilarity) / (1 + level * LEVEL_PENELTY); impactList.AddLast(tmp); } } // Call the next TrackerCase to analyze foreach (TrackerCase next in relatedCases) { if (!next.Visited) { impactList = next.FindImpact(impactList, level + 1, startSimilarity); } } return impactList; }
/// Creates a Spreadsheet that is a duplicate of the spreadsheet saved in source. /// /// See the AbstractSpreadsheet.Save method and Spreadsheet.xsd for the file format /// specification. /// /// If there's a problem reading source, throws an IOException. /// /// Else if the contents of source are not consistent with the schema in Spreadsheet.xsd, /// throws a SpreadsheetReadException. /// /// Else if the IsValid string contained in source is not a valid C# regular expression, throws /// a SpreadsheetReadException. (If the exception is not thrown, this regex is referred to /// below as oldIsValid.) /// /// Else if there is a duplicate cell name in the source, throws a SpreadsheetReadException. /// (Two cell names are duplicates if they are identical after being converted to upper case.) /// /// Else if there is an invalid cell name or an invalid formula in the source, throws a /// SpreadsheetReadException. (Use oldIsValid in place of IsValid in the definition of /// cell name validity.) /// /// Else if there is an invalid cell name or an invalid formula in the source, throws a /// SpreadsheetVersionException. (Use newIsValid in place of IsValid in the definition of /// cell name validity.) /// /// Else if there's a formula that causes a circular dependency, throws a SpreadsheetReadException. /// /// Else, create a Spreadsheet that is a duplicate of the one encoded in source except that /// the new Spreadsheet's IsValid regular expression should be newIsValid. public Spreadsheet(TextReader source, Regex newIsValid) { cds = new CellDS(); LinkedList <string> names = new LinkedList <string>(); LinkedList <string> contentsList = new LinkedList <string>(); using (var xmr = XmlReader.Create(source)) { while (xmr.Read()) { if (xmr.IsStartElement()) { switch (xmr.Name) { case "spreadsheet": IsValid = xmr["IsValid"]; if (IsValid == null) { throw new SpreadsheetReadException("is valid didnt read properly"); } break; case "cell": var temp = xmr["name"]; if (names.Contains(temp)) { throw new SpreadsheetReadException("duplicite cell names"); } try { if (!Regex.IsMatch(temp, IsValid)) { throw new SpreadsheetReadException("source file unreadable"); } } catch (ArgumentException e) { throw new SpreadsheetReadException(e.Message); } names.AddLast(temp); if (temp == null) { throw new SpreadsheetReadException("a name didnt read properly"); } //deal with the contents string form = xmr["contents"]; if (form == null) { throw new SpreadsheetReadException("contents didnt read properly"); } if (form.Substring(0, 1).Equals("=")) { try { new Formula(form.Substring(1), (s => s), checkIfValidName); } catch (FormulaFormatException e) { throw new SpreadsheetReadException("source file unreadable, bad formula"); } } contentsList.AddLast(form); break; default: throw new IOException(); } } } } IsValid = newIsValid.ToString(); int i = 0; try { foreach (string s in names) { SetContentsOfCell(s, contentsList.ElementAt(i)); i++; } } catch (Exception) { throw new SpreadsheetVersionException("bad regex on new file"); } if (names.Count != contentsList.Count) { throw new SpreadsheetVersionException("uneven data matches"); } }
/// <summary> /// Calculates a path from start to end. When no path can be found in /// reasonable time the search is aborted and an incomplete path is returned. /// When refresh is not set to true a cached path is returned where possible. /// </summary> /// <param name="start">start position in 2d map space</param> /// <param name="end">end position in 2d map space</param> /// <param name="refresh">force to recalculate the path</param> /// <returns></returns> public TilePath CalculatePath(Point2D start, Point2D end, bool refresh) { // swap points to calculate the path backwards (from end to start) Point2D temp = end; end = start; start = temp; // Check whether the requested path is already known var request = new TilePathRequest(start, end); if (!refresh && mPathCache.ContainsKey(request)) { return(mPathCache[request].Copy()); } // priority queue of nodes that yet have to be explored sorted in // ascending order by node costs (F) var open = new AutoPriorityQueue <TilePathNode>(); // List of nodes that have already been explored var closed = new LinkedList <ITileCell>(); // Start is to be explored first var startNode = new TilePathNode(null, mLayer.GetCell(start), end); open.Enqueue(startNode); var steps = 0; do { // Examine the cheapest node among the yet to be explored var current = open.Dequeue(); // Finish? if (current.Cell.Matches(end) || ++steps > mStepLimit) { // Paths which lead to the requested goal are cached for reuse var path = new TilePath(current); if (mPathCache.ContainsKey(request)) { mPathCache[request] = path.Copy(); } else { mPathCache.Add(request, path.Copy()); } return(path); } // Explore all neighbours of the current cell var neighbours = mLayer.GetNeighbourCells(current.Cell); foreach (var cell in neighbours) { // Discard nodes that are not of interest var flag = mCollisionLayer[cell.X, cell.Y]; if (closed.Contains(cell) || (cell.Matches(end) == false && (flag & ECollisionType.NotMoveable) != ECollisionType.NotMoveable)) { continue; } // Successor is one of current's neighbours var successor = new TilePathNode(current, cell, end); var contained = open.Find(successor); if (contained != null && successor.CostTotal >= contained.CostTotal) { // This cell is already in the open list represented by // another node that is cheaper continue; } if (contained != null && successor.CostTotal < contained.CostTotal) { // This cell is already in the open list but on a more expensive // path -> "integrate" the node into the current path contained.Predecessor = current; contained.Update(); open.Update(contained); } else { // The cell is not in the open list and therefore still has to // be explored open.Enqueue(successor); } } // Add current to the list of the already explored nodes closed.AddLast(current.Cell); } while (open.Peek() != null); return(null); }
bool Contains(T x) { LinkedList <T> whichList = m_theLists[MyHash(x)]; return(whichList.Contains(x)); }
public void Find_Empty() { LinkedList<int> list = new LinkedList<int>(); Assert.IsFalse(list.Contains(10), "Nothing should have been found."); }
/// <summary> /// returns a path to the target that avoids obstacles /// </summary> /// <param name="targetCoords">Target</param> /// <param name="unit">Model containing info about the unit's location</param> /// <returns>Path</returns> /// <exception cref="NoPathFoundException">Throws exception when no path found</exception> public List <FloatCoords> FindPath(FloatCoords targetCoords, LocationModel unit) { if (IsCellImpassable(worldController.GetCellFromCoords((Coords)targetCoords).worldCellModel, unit)) { throw new NoPathFoundException(unit.Coords, (Coords)targetCoords); } CoordsCalculator unitCoordsCalculator = new CoordsCalculator(unit.FloatCoords); CoordsCalculator targetCoordsCalculator = new CoordsCalculator(targetCoords); LinkedList <FloatCoords> currentPath = new LinkedList <FloatCoords>(); List <Coords> visitedCoords = new List <Coords>(); FloatCoords currentCoords = unit.FloatCoords; bool IsPreviousNode(Coords target) => currentPath.Last?.Previous != null && (Coords)currentPath.Last.Previous.Value == target; while ((Coords)currentCoords != (Coords)targetCoords) { Dictionary <Coords, CellWeightValues> currentNeighbours = CalculateNeighboursWeights((Coords)currentCoords, (Coords)targetCoords, unit); // Find most probable cell, // WHERE: // 1. NOT Cell has been visited and isn't the previous node List <FloatCoords> mostProbableCandidates = ( from KeyValuePair <Coords, CellWeightValues> pair in currentNeighbours where !(visitedCoords.Contains(pair.Key) && !IsPreviousNode(pair.Key)) && !IsDiagonalPathBlocked((Coords)currentCoords, pair.Key, unit) let cellWeightValues = pair.Value orderby cellWeightValues.Weight, cellWeightValues.AbsoluteDistanceToTarget select(FloatCoords) pair.Key).ToList(); if (!mostProbableCandidates.Any()) { throw new NoPathFoundException(unit.Coords, (Coords)targetCoords); } FloatCoords mostProbableCoords = mostProbableCandidates.First(); if (ENABLE_ANIMATION) { worldController.GetCellFromCoords((Coords)currentCoords).worldCellView.Colour = Color.Red; worldController.GetCellFromCoords((Coords)mostProbableCoords).worldCellView.Colour = Color.Blue; Thread.Sleep(ANIMATION_DELAY_MILLIS); } if (!visitedCoords.Contains((Coords)mostProbableCoords)) { visitedCoords.Add((Coords)mostProbableCoords); } // Add to list if mostProbableCoords: // 1. The path is empty // 2. OR the node isn't in the path AND it isn't too far away // Else, if mostProbableCoords is already known, move to that node if (!currentPath.Any() || !currentPath.Contains(mostProbableCoords) && !(unitCoordsCalculator.DistanceToFloatCoords(mostProbableCoords) > SearchLimit || targetCoordsCalculator.DistanceToFloatCoords(mostProbableCoords) > SearchLimit)) { currentPath.AddLast(mostProbableCoords); } else if (currentPath.Contains(mostProbableCoords)) { while ((Coords)currentPath.Last.Value != (Coords)mostProbableCoords) { currentPath.RemoveLast(); } } currentCoords = currentPath.Last.Value; } if (!currentPath.Any()) { throw new NoPathFoundException(unit.Coords, (Coords)targetCoords); } Queue <FloatCoords> route = ReduceWaypoints(currentPath.ToList(), unit); return(route.ToList()); }