public override Tree<SyntaxToken> Read(LinkedList<MixedToken> tokens, Grammar grammar) { // Do not create negate syntax token if we are able to create a subtract syntax token var lastNegateNode = tokens.FindLastNode(t => t.Value.IsLexicToken && t.Value.LexicToken is SubtractToken && (t.Previous != null && !t.Previous.Value.IsTree || t.Previous == null)); if (lastNegateNode != null) { var next = lastNegateNode.Next; if (next == null) throw new ParserException("Unexpected argument of 'negate' operator."); if (!next.Value.IsTree) throw new ParserException("Argument of 'negate' operator was not parsed."); NegateSyntaxToken token = new NegateSyntaxToken(); Tree<SyntaxToken> tree = new Tree<SyntaxToken>(token); tree.Leafs.Add(next.Value.Tree); tokens.AddBefore(lastNegateNode, new MixedToken(tree)); tokens.Remove(lastNegateNode); tokens.Remove(next); return tree; } return null; }
static void Main(string[] args) { LinkedList<string> sporcular = new LinkedList<string>(); sporcular.AddLast("A"); sporcular.AddLast("B"); sporcular.AddLast("C"); sporcular.AddLast("D"); sporcular.AddLast("E"); sporcular.AddLast("F"); sporcular.AddLast("G"); sporcular.AddLast("H"); sporcular.Remove("H"); sporcular.AddFirst("H"); sporcular.Remove("E"); sporcular.AddFirst("E"); sporcular.AddAfter(sporcular.First, "X"); LinkedListNode<string> c = sporcular.Find("C"); sporcular.AddBefore(c, "Y"); foreach (string item in sporcular) { Console.WriteLine(item); } }
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(); }
// 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(string[] args) { //creates a linked list LinkedList<string> linked1 = new LinkedList<string>(); //appending three elements to the list linked1.AddLast("One"); linked1.AddLast("Two"); linked1.AddLast("Three"); linked1.AddFirst("Zero"); PrintLinked1(linked1); Console.WriteLine(); //insterting a node between element "Two" and "Three" LinkedListNode<string> myNode = linked1.Find("Three"); linked1.AddBefore(myNode, "Inserted using add before."); PrintLinked1(linked1); //removing one element linked1.Remove("One"); PrintLinked1(linked1); //remove Three using myNode myNode = linked1.Find("Three"); linked1.Remove(myNode); PrintLinked1(linked1); }
static void Main(string[] args) { var testArr = new LinkedList<int>(); Console.WriteLine("Elements:"); testArr.Add(1); testArr.Add(4); testArr.Add(-1); testArr.ForEach(e => Console.Write(e + " ")); Console.WriteLine(); Console.WriteLine("Count:"); Console.WriteLine(testArr.Count()); Console.WriteLine("Remove element [1]:"); testArr.Remove(1); testArr.ForEach(e => Console.Write(e + " ")); Console.WriteLine(); Console.WriteLine("Count:"); Console.WriteLine(testArr.Count()); Console.WriteLine("Remove element [1]:"); testArr.Remove(1); testArr.ForEach(e => Console.Write(e + " ")); Console.WriteLine(); Console.WriteLine("Count:"); Console.WriteLine(testArr.Count()); Console.WriteLine("Remove element [0]:"); testArr.Remove(0); testArr.ForEach(e => Console.Write(e + " ")); Console.WriteLine(); Console.WriteLine("Count:"); Console.WriteLine(testArr.Count()); testArr.Add(3); testArr.Add(5); testArr.Add(7); testArr.Add(0); Console.WriteLine("Enum:"); foreach (var element in testArr) { Console.WriteLine(element); } Console.WriteLine("Elements:"); testArr.ForEach(e => Console.Write(e + " ")); Console.WriteLine(); Console.WriteLine("Index of 5"); Console.WriteLine(testArr.FirstIndexOf(5)); testArr.Add(3); testArr.Add(9); Console.WriteLine("Last Index of 3"); Console.WriteLine("Elements:"); testArr.ForEach(e => Console.Write(e + " ")); Console.WriteLine(); Console.WriteLine(testArr.LastIndexOf(3)); }
/* 11. Implement the data structure linked list. Define a class ListItem<T> that has two fields: value (of type T) and NextItem (of type ListItem<T>). * Define additionally a class LinkedList<T> with a single field FirstElement (of type ListItem<T>).*/ /// <summary> /// Mains the specified args. /// </summary> public static void Main() { LinkedList<int> testList = new LinkedList<int>(); // Console.WriteLine(testList); testList.AddFirst(1); testList.AddFirst(2); testList.AddFirst(8); testList.AddFirst(1); testList.AddLast(3); testList.AddLast(5); testList.Remove(1); testList.Remove(5); Console.Write(testList); }
static void Main() { LinkedList<int> linkedList = new LinkedList<int>(); linkedList.Add(5); linkedList.Add(10); Console.WriteLine(linkedList.Head.Value); Console.WriteLine(linkedList.Head.NextNode.Value); linkedList.Remove(1); Console.WriteLine(linkedList.Head.Value); Console.WriteLine(linkedList.Count); linkedList.Remove(0); Console.WriteLine(linkedList.Count); linkedList.Add(1); linkedList.Add(2); linkedList.Add(3); linkedList.Add(4); linkedList.Add(5); linkedList.Add(1); Console.WriteLine(linkedList.FirstIndexOf(1)); Console.WriteLine(linkedList.FirstIndexOf(20)); Console.WriteLine(linkedList.LastIndexOf(1)); Console.WriteLine(linkedList.LastIndexOf(20)); Console.WriteLine(); Console.WriteLine("Foreached: "); foreach (int value in linkedList) { Console.WriteLine(value); } Console.WriteLine(); Console.WriteLine("Indexes: "); Console.WriteLine(linkedList[0]); Console.WriteLine(linkedList[1]); Console.WriteLine(linkedList[2]); Console.WriteLine(linkedList[3]); Console.WriteLine(linkedList[4]); Console.WriteLine(linkedList[5]); // Console.WriteLine(linkedList[6]); // Exception Console.WriteLine("Changing the values"); linkedList[0] = 20; linkedList[1] = 30; Console.WriteLine(linkedList[0]); Console.WriteLine(linkedList[1]); }
static void Main(string[] args) { LinkedList<string> myList = new LinkedList<string>(); myList.Add("element"); myList.Add("element2"); myList.Add("element3"); myList.Add("element4"); myList.Add("element5"); myList.Add("element6"); myList.Add("element6"); myList.Add("element6"); myList.Add("element6"); myList.Add("element6"); myList.Add("element4"); myList.Add("element4"); myList.Add("element4"); myList.Remove(2); foreach (var element in myList) { Console.WriteLine(element); } Console.WriteLine(myList.GetCurrent); Console.WriteLine(myList.First); Console.WriteLine(myList.FirstIndexOf("item")); Console.WriteLine(myList.LastIndexOf("element6")); }
static void Main(string[] args) { List<int> list = new List<int> { 3,2, }; // 3, 2 list.Add(5); // 3, 2, 5 list.Add(6); // 3, 2, 5, 6 list.Remove(5); // 3, 2, 6 Queue<int> queue = new Queue<int>(); queue.Enqueue(3);// 3 queue.Enqueue(8);// 3, 8 queue.Dequeue(); // 8 Stack<int> stack = new Stack<int>(); stack.Push(2); // 2 stack.Push(7); // 7, 2 stack.Push(8); // 8, 7, 2 stack.Pop(); // 7, 2 foreach (var i in stack) { Console.WriteLine(i); } LinkedList<int> linkedList = new LinkedList<int>(); linkedList.AddFirst(9); // 9 linkedList.AddAfter(linkedList.Find(9), 5); // 9, 5 linkedList.Remove(9); // 5 Console.Read(); }
public static void Run() { string[] line = Console.ReadLine().Split(' '); int n = Convert.ToInt32(line[0]), x1 = Convert.ToInt32(line[1]), y1 = Convert.ToInt32(line[2]), x2 = Convert.ToInt32(line[3]), y2 = Convert.ToInt32(line[4]); LinkedList<Flower> first = new LinkedList<Flower>(); LinkedList<Flower> second = new LinkedList<Flower>(); for (int i = 0; i < n; i++) { line = Console.ReadLine().Split(' '); int x = Convert.ToInt32(line[0]), y = Convert.ToInt32(line[1]); first.AddLast(new Flower { x = x, y = y, dist = (long)(x - x1) * (long)(x - x1) + (long)(y - y1) * (long)(y - y1) }); } long res = long.MaxValue; for (int i = 0; i <= n; i++) { Flower firstmax = first.Count > 0 ? first.Aggregate((c, d) => c.dist > d.dist ? c : d) : null; Flower secondmax = second.Count > 0 ? second.Aggregate((c, d) => c.dist > d.dist ? c : d) : null; long d1 = 0, d2 = 0; if (firstmax != null) d1 = firstmax.dist; if (secondmax != null) d2 = secondmax.dist; res = Math.Min(res, d1 + d2); if (firstmax != null) { first.Remove(firstmax); firstmax.dist = (long)(firstmax.x - x2) * (long)(firstmax.x - x2) + (long)(firstmax.y - y2) * (long)(firstmax.y - y2); second.AddLast(firstmax); } } Console.WriteLine(res); }
// Update is called once per frame void Update() { var destination = (Vector2)traker.Markers.First.Value.position; var arrived = new Queue<Pikmin>(); var candidates = new LinkedList<Pikmin>(); foreach (var pik in pikmins.pikmins) { var toDest = destination - (Vector2)pik.transform.position; var hys = pik.state != Pikmin.State.Other ? + hysteresis : - hysteresis; if (toDest.sqrMagnitude < arrivalDistance * arrivalDistance + hys) { pik.state = Pikmin.State.Friend; arrived.Enqueue(pik); } else { pik.state = Pikmin.State.Other; candidates.AddLast(pik); } } while (arrived.Count > 0) { var pik = arrived.Dequeue(); var cand = candidates.First; while (cand != null) { var toArrived = (Vector2)pik.transform.position - (Vector2)cand.Value.transform.position; var hys = cand.Value.state != Pikmin.State.Other ? + hysteresis : - hysteresis; if (toArrived.sqrMagnitude < arrivalDistance * arrivalDistance + hys) { arrived.Enqueue(cand.Value); candidates.Remove(cand); cand.Value.state = Pikmin.State.Relation; } cand = cand.Next; } } }
public static void CalculateTime(LinkedList<string> list, int k) { // Add var startAdding = DateTime.Now; string test = "Test string"; for (int i = 0; i < k; i++) { list.AddFirst(test); } var finishAdding = DateTime.Now; Console.WriteLine("Addition time (" + k + " elements) : " + list.GetType() + " " + (finishAdding - startAdding)); // Search var startSearch = DateTime.Now; for (int i = 0; i < k; i++) { bool a = list.Equals(test); } var finishSearch = DateTime.Now; Console.WriteLine("Search time (" + k + " elements) : " + list.GetType() + " " + (finishSearch - startSearch)); // Remove k = 1000000; var startRemoving = DateTime.Now; for (int i = 0; i < k; i++) { list.Remove(test); } var finishRemoving = DateTime.Now; Console.WriteLine("Removal time (" + k + " elements) : " + list.GetType() + " " + (finishRemoving - startRemoving) + "\n"); }
private static UncertainValue Integrate_Adaptive(MultiFunctor f, CoordinateTransform[] map, IntegrationRegion r, EvaluationSettings settings) { // Create an evaluation rule GenzMalik75Rule rule = new GenzMalik75Rule(r.Dimension); // Use it on the whole region and put the answer in a linked list rule.Evaluate(f, map, r); LinkedList<IntegrationRegion> regionList = new LinkedList<IntegrationRegion>(); regionList.AddFirst(r); // Iterate until convergence while (f.EvaluationCount < settings.EvaluationBudget) { // Add up value and errors in all regions. // While we are at it, take note of the region with the largest error. double value = 0.0; double error = 0.0; LinkedListNode<IntegrationRegion> regionNode = regionList.First; double maxError = 0.0; LinkedListNode<IntegrationRegion> maxErrorNode = null; while (regionNode != null) { IntegrationRegion region = regionNode.Value; value += region.Value; error += region.Error; //error += MoreMath.Sqr(region.Error); if (region.Error > maxError) { maxError = region.Error; maxErrorNode = regionNode; } regionNode = regionNode.Next; } // Check for convergence. if ((error <= settings.AbsolutePrecision) || (error <= settings.RelativePrecision * Math.Abs(value))) { return (new UncertainValue(value, error)); } // Split the region with the largest error, and evaluate each subregion. IntegrationRegion maxErrorRegion = maxErrorNode.Value; regionList.Remove(maxErrorNode); IList<IntegrationRegion> subRegions = maxErrorRegion.Split(maxErrorRegion.SplitIndex); /* Countdown cnt = new Countdown(2); ThreadPool.QueueUserWorkItem((object state) => { rule.Evaluate(f, subRegions[0]); cnt.Signal(); }); ThreadPool.QueueUserWorkItem((object state) => { rule.Evaluate(f, subRegions[1]); cnt.Signal(); }); cnt.Wait(); foreach (IntegrationRegion subRegion in subRegions) { regionList.AddLast(subRegion); } */ foreach (IntegrationRegion subRegion in subRegions) { rule.Evaluate(f, map, subRegion); regionList.AddLast(subRegion); } } throw new NonconvergenceException(); }
public IEnumerable<IStory> Solve(int capacity, IEnumerable<IStory> candidates) { if (capacity < 0) throw new ArgumentException("Argument must be greater than zero", "capacity"); if (candidates == null) throw new ArgumentNullException("candidates"); var candidateList = new LinkedList<IStory>(candidates.OrderBy(x => x.Priority).ThenByDescending(x => x.Points)); int capacityLeft = capacity; bool candidateFound = true; List<IStory> solution = new List<IStory>(); while (capacityLeft > 0 && candidateFound) { candidateFound = false; foreach (var candidate in candidateList) { if (capacityLeft >= candidate.Points) { solution.Add(candidate); capacityLeft -= candidate.Points; candidateList.Remove(candidate); candidateFound = true; break; } } } return solution; }
public static string ExecutePrintAllTheatresCommand() { var theatresCount = ThatreMain.universal.ListTheatres().Count(); if (theatresCount > 0) { var resultTheatres = new LinkedList<string>(); for (int i = 0; i < theatresCount; i++) { ThatreMain.universal.ListTheatres() .Skip(i) .ToList() .ForEach(t => resultTheatres.AddLast(t)); foreach (var t in ThatreMain.universal.ListTheatres().Skip(i + 1)) { resultTheatres.Remove(t); } } return String.Join(", ", resultTheatres); } return "No theatres"; }
static void Main() { LinkedList<int> collection = new LinkedList<int>(new int[] { 4, 2, 2, 5, 2, 3, 2, 3, 1, 5, 2 }); Dictionary<int, int> countedNumbers = new Dictionary<int, int>(); foreach (var item in collection) { if (countedNumbers.ContainsKey(item)) { countedNumbers[item] = countedNumbers[item] + 1; } else { countedNumbers.Add(item, 1); } } LinkedListNode<int> currentNode = collection.First; while (currentNode != null) { if (countedNumbers[currentNode.Value] % 2 != 0) { int toRemove = currentNode.Value; currentNode = currentNode.Next; collection.Remove(toRemove); } else { currentNode = currentNode.Next; } } Console.WriteLine(String.Join(",", collection)); }
public static void Main(string[] args) { /* Creating a Simple Linked List */ LinkedList<Object> MyLinkedList = new LinkedList<Object>(); /* Inserting Elements */ MyLinkedList.AddLast ("Add"); MyLinkedList.AddLast(4); /* Implementing Find */ MyLinkedList.AddAfter(MyLinkedList.Find("Add"), 'a'); /* Printing Elements of the List */ PrintList (MyLinkedList); /* Remove a particular element from the List */ MyLinkedList.Remove (4); PrintList (MyLinkedList); /* Printing the Count of the List */ int linkedListCount = MyLinkedList.Count; Console.WriteLine (linkedListCount); }
static void Main() { LinkedList<int> numbers = new LinkedList<int>(); Console.WriteLine("Enter some numbers: "); bool isNumber = true; while (isNumber) { int number; isNumber = int.TryParse(Console.ReadLine(), out number); if (isNumber) { numbers.AddLast(number); } } var node = numbers.First; while (node != null) { var next = node.Next; if (node.Value < 0) numbers.Remove(node); node = next; } Console.WriteLine(string.Join(" -> ", numbers)); }
public void RemoveFirstAndAdd() { LinkedList<int> list = new LinkedList<int> { 1, 2, 3 }; list.Remove(1); list.AddFirst(0); CollectionAssert.AreEqual(new[] { 0, 2, 3 }, list); }
public void RemoveLastAndAdd() { LinkedList<int> list = new LinkedList<int> { 1, 2, 3 }; list.Remove(3); list.Add(4); CollectionAssert.AreEqual(new[] { 1, 2, 4 }, list); }
/// <summary> /// Finds the control. /// </summary> /// <param name="parent">The parent.</param> /// <param name="controlID">The control ID.</param> /// <returns></returns> public static Control FindControlRecursive(this Control parent, string controlId) { Control current = parent; LinkedList<Control> controlList = new LinkedList<Control>(); while (current != null) { if (current.ID == controlId) { return current; } foreach (Control child in current.Controls) { if (child.ID == controlId) { return child; } if (child.HasControls()) { controlList.AddLast(child); } } if (controlList.Count == 0) { return null; } current = controlList.First.Value; controlList.Remove(current); } return null; }
internal void Forget(Awaiter awaiter) { lock (_stateLock) { _awaiters?.Remove(awaiter); } }
public static void Main() { LinkedList<int> testList = new LinkedList<int>(); for (int i = 0; i < 10; i++) { testList.Add(i); } foreach (var number in testList) { Console.Write(number + ", "); } Console.WriteLine("Count={0}", testList.Count); testList.Remove(9); foreach (var number in testList) { Console.Write(number + ", "); } Console.WriteLine("Count={0}", testList.Count); testList.Add(1); foreach (var number in testList) { Console.Write(number + ", "); } Console.WriteLine("Count={0}", testList.Count); Console.WriteLine("First index of 1={0}", testList.FirstIndexOf(1)); Console.WriteLine("Last index of 1={0}", testList.LastIndexOf(1)); }
private CardStack CreateCardStack() { // generate list of cards var cards = new LinkedList<Card>(); foreach (var color in Enum.GetValues(typeof(CardColor)).OfType<CardColor>()) foreach (var filling in Enum.GetValues(typeof(Filling)).OfType<Filling>()) foreach (var shape in Enum.GetValues(typeof(Shape)).OfType<Shape>()) for (byte shapeIndex = 0; shapeIndex < 3; shapeIndex++) cards.AddLast(new Card() { Color = color, Filling = filling, Shape = shape, ShapeCount = (byte) (shapeIndex + 1) }); // shake cards var shakedCards = new CardStack(); Random rnd = new Random(23); for (int cardsIndex = cards.Count - 1; cardsIndex >= 0; cardsIndex--) { var cardIndexToMove = (int)Math.Floor(cardsIndex * rnd.NextDouble()); var cardToMove = cards.Skip(cardIndexToMove).Take(1).Single(); shakedCards.Push(cardToMove); cards.Remove(cardToMove); } return shakedCards; }
static void Main() { string line = "3 -9 6 -5 55 84 22 6 -55 56 -100 22"; string[] elements = line.Split(' '); LinkedList<int> list = new LinkedList<int>(); foreach (string element in elements) { list.AddLast(int.Parse(element)); } Console.WriteLine("The list before removing all the negative elements:"); Console.WriteLine(string.Join(", ", list)); var firstElement = list.First; while (firstElement != null) { var nextElement = firstElement.Next; if (firstElement.Value < 0) { list.Remove(firstElement); } firstElement = nextElement; } Console.WriteLine("The list after removing all the negative elements:"); Console.WriteLine(string.Join(", ", list)); }
public void Solve(StreamWriter writer, StreamReader reader) { var list = new LinkedList<int>(Enumerable.Range(1, 100)); var current = list.First.Next; while (current != null) { var value = current.Value; var removing = list.First; while (removing != null) { for (int i = 1; i < value && removing != null; i++) removing = removing.Next; if (removing == null) break; if (removing == current) current = current.Previous; var next = removing.Next; list.Remove(removing); removing = next; } current = current.Next; } }
public static void Main() { try { LinkedList list = new LinkedList(); Console.WriteLine("It is {0} that this list in empty", list.IsEmpty()); list.Insert("Happy days"); list.Insert("Pie in the sky"); list.Insert("Trouble in River City"); Console.WriteLine("The original list is:"); list.Display(); list.Reset(); list.Advance(); Console.WriteLine("The current list element is {0}", list.GetData()); list.Remove(); Console.WriteLine("The list, after removing the current element, is:"); list.Display(); } catch (Exception e) { Console.WriteLine(e); } Console.WriteLine("Hit any key to exit"); Console.ReadLine(); }
/* Ultra-duper mega cool code snippet from StackOverflow - It'll save your life one day! */ private static Control FindControlIterative(Control root, string id) { Control ctl = root; var ctls = new LinkedList<Control>(); while (ctl != null) { if (ctl.ID == id) return ctl; foreach (Control child in ctl.Controls) { if (child.ID == id) return child; if (child.HasControls()) ctls.AddLast(child); } if (ctls.First != null) { ctl = ctls.First.Value; ctls.Remove(ctl); } else return null; } return null; }
public static void RemoveNumberThatOccurOddTimes(LinkedList<int> sequence) { Dictionary<int, int> countNumbers = new Dictionary<int, int>(); foreach (var number in sequence) { if (!countNumbers.ContainsKey(number)) { countNumbers[number] = 0; } countNumbers[number]++; } var currentNumber = sequence.First; while (currentNumber != null) { if (countNumbers[currentNumber.Value] % 2 != 0) { var toRemove = currentNumber; currentNumber = currentNumber.Next; sequence.Remove(toRemove); } else { currentNumber = currentNumber.Next; } } }
static void SashaAndKate() { var input = Console.ReadLine().Split().ToArray(); string n = input[0]; int k = int.Parse(input[1]); var p = new LinkedList<char>(n); var current = p.First; while (0 < k && current != p.Last) { var next = current.Next; if (current.Value < next.Value) { //p.RemoveFirst(); p.Remove(current); k--; //current = p.First; current = next.Previous ?? p.First; } else { current = next; } } while (0 < k--) p.RemoveLast(); foreach (char node in p) Console.Write(node); }
public void RemoveItem(Item item) { items.Remove(item); }
private static void runBackup(Plan Plan) { dirs = new LinkedList <string>(); files = new LinkedList <string>(); Plan.Status = PlanStatus.Running; Plan.LastAttmpted = DateTime.Now; dirs.AddLast(Plan.Source); curPlan = Plan; executionStatus = new PlanExecutionStatus(); switch (Plan.DestinationType) { case LocationType.Directory: destinationType = new DestTypes.Directory(); break; case LocationType.CompressedDirectory: destinationType = new DestTypes.DirectoryCompressed(); break; default: System.Windows.Forms.MessageBox.Show("Ah! Unknown destination type!"); throw new Exception(); } int numFiles, numDirs; Status stat; #region Get info on next thing to run lock (plans) { numFiles = files.Count; numDirs = dirs.Count; stat = status; } #endregion while (stat != DPend_Backup.Status.Stopping && (numDirs > 0 || numFiles > 0 || workerThreads.Count > 0)) { #region Trim worker thread list LinkedListNode <System.Threading.Thread> node = workerThreads.First; while (node != null) { if (node.Value.ThreadState == System.Threading.ThreadState.Aborted || node.Value.ThreadState == System.Threading.ThreadState.Stopped) { LinkedListNode <System.Threading.Thread> next = node.Next; workerThreads.Remove(node); node = next; } else { node = node.Next; } } #endregion #region Fire up more workers as needed if (workerThreads.Count < curPlan.NumberWorkers && (numDirs > 0 | numFiles > 0)) { System.Threading.Thread thr = new System.Threading.Thread(new System.Threading.ThreadStart(runBackupWorker)); thr.Priority = System.Threading.ThreadPriority.Lowest; thr.Start(); workerThreads.AddLast(thr); } #endregion #region Wait around for a bit System.Threading.Thread.Sleep(500); #endregion #region Get info on next thing to run lock (plans) { numFiles = files.Count; numDirs = dirs.Count; stat = status; } #endregion } if (numDirs == 0 && numFiles == 0 && workerThreads.Count == 0) { Plan.LastRun = Plan.LastAttmpted; Plan.Status = PlanStatus.OK; SaveSettings(); lock (plans) { if (curPlan == Plan) { curPlan = null; } else { stat = DPend_Backup.Status.Stopping; } } } }
public TValue Get(TKey key) { if (key == null) { Log.To.NoDomain.E(Tag, "key cannot be null in Get, throwing..."); throw new ArgumentNullException("key"); } Log.To.NoDomain.D(Tag, "Entering first lock in Get"); TValue mapValue; lock (_locker) { mapValue = _recents.Get(key); if (mapValue != null) { Log.To.NoDomain.V(Tag, "LruCache hit for {0}, returning {1}...", new SecureLogString(key, LogMessageSensitivity.PotentiallyInsecure), new SecureLogString(mapValue, LogMessageSensitivity.PotentiallyInsecure)); HitCount++; _nodes.Remove(key); _nodes.AddFirst(key); return(mapValue); } MissCount++; Log.To.NoDomain.V(Tag, "LruCache miss for {0}, searching alive objects...", new SecureLogString(key, LogMessageSensitivity.PotentiallyInsecure)); var mapValueRef = _allValues.Get(key); if (mapValueRef != null && mapValueRef.TryGetTarget(out mapValue)) { Log.To.NoDomain.V(Tag, "...Alive object {0} found!", new SecureLogString(mapValue, LogMessageSensitivity.PotentiallyInsecure)); Put(key, mapValue); return(mapValue); } Log.To.NoDomain.V(Tag, "...No alive object found!"); _allValues.Remove(key); } Log.To.NoDomain.D(Tag, "Exited first lock in Get"); TValue createdValue = Create(key); if (createdValue == null) { return(default(TValue)); } Log.To.NoDomain.V(Tag, "Autocreated default object {0}, inserting into cache", new SecureLogString(createdValue, LogMessageSensitivity.PotentiallyInsecure)); Log.To.NoDomain.D(Tag, "Entering second lock in Get"); lock (_locker) { CreateCount++; mapValue = _recents.Get(key); _recents[key] = createdValue; _nodes.Remove(key); _nodes.AddFirst(key); if (mapValue != null) { Log.To.NoDomain.W(Tag, "Cache already has a value for {0}, aborting insert", new SecureLogString(key, LogMessageSensitivity.PotentiallyInsecure)); // There was a conflict so undo that last put _recents[key] = mapValue; } else { Size += SafeSizeOf(key, createdValue); } } Log.To.NoDomain.D(Tag, "Exited second lock in Get"); if (mapValue != null) { EntryRemoved(false, key, createdValue, mapValue); return(mapValue); } else { Trim(); return(createdValue); } }
//Boton Analizar Entrada private void button1_Click(object sender, EventArgs e) { ListaImagenes = new LinkedList <string>(); pictureBox1.Image = null; pictureBox1.Visible = false; button2.Enabled = false; button3.Enabled = false; imagen_actual = -1; String entrada; foreach (Control item in this.tabControl1.SelectedTab.Controls) { Boolean a = typeof(RichTextBox).IsInstanceOfType(item); if (a) { //Recuperando texto del RichTextBox de la pestaña seleccionada para el analisis. entrada = item.Text; entrada += "#"; AnalizadorLexico lexico = new AnalizadorLexico(); LinkedList <Token> listaTokens = lexico.Analizar(entrada); richTextBox1.Text = "**Inicia Análisis Léxico**\n"; richTextBox1.Text += lexico.imprimirListaToken(listaTokens); richTextBox1.Text += "**Finaliza Análisis Léxico**\n"; AnalizadorER analizadorER = new AnalizadorER(); //Si la lista de tokens del léxico no está vacía... if (listaTokens.Count > 0) { //Si no hay error en el análisis de la entrada procede a realizar el sintáctico. if (!lexico.existenciaError) { richTextBox1.Text += "**Inicia Análisis Sintáctico**\n"; ListaTokens = analizadorER.Parsear(listaTokens); for (int i = 0; i < ListaTokens.Count; i++) { Token token = ListaTokens.ElementAt(i); if (token.GetTipo() == Token.Tipo.INDEFINIDO) { ListaTokens.Remove(token); ListaErrores.AddLast(token); } } //Se intenta recuperar las imagenes generadas. if (analizadorER.RutasImagenes.Count > 0) { ListaImagenes = analizadorER.RutasImagenes; pictureBox1.Visible = true; pictureBox1.Image = System.Drawing.Image.FromFile(ListaImagenes.First.Value); imagen_actual = 0; if (ListaImagenes.Count > 1) { button3.Enabled = true; } }//Se imprimen los resultados del análisis sintáctico. if (!analizadorER.existenciaErrorSintactico) { richTextBox1.Text += analizadorER.consola; richTextBox1.Text += "*SIN ERRORES SINTACTICOS*\n**Finaliza Análisis Sintáctico**\n"; } else { richTextBox1.Text += analizadorER.consola + "**Finaliza Análisis Sintáctico**\n"; } } else { richTextBox1.Text += "Se encontraron errores léxicos. No puede iniciar análsis sintáctico\n"; foreach (Token error in listaTokens) { if (error.GetTipo() == Token.Tipo.INDEFINIDO) { ListaErroresLexico.AddLast(error); } } } } else { richTextBox1.Text += "El analisis lexico no devolvió ningún token. No puede iniciar análsis sintáctico\n"; } } } }
/// <summary> /// Adds epsilon transitions to the given automaton. This method adds extra /// character interval transitions that are equivalent to the given set of /// epsilon transitions. /// </summary> /// <param name="a"> Automaton. </param> /// <param name="pairs"> Collection of <see cref="StatePair"/> objects representing pairs of /// source/destination states where epsilon transitions should be /// added. </param> public static void AddEpsilons(Automaton a, ICollection <StatePair> pairs) { a.ExpandSingleton(); Dictionary <State, HashSet <State> > forward = new Dictionary <State, HashSet <State> >(); Dictionary <State, HashSet <State> > back = new Dictionary <State, HashSet <State> >(); foreach (StatePair p in pairs) { HashSet <State> to; if (!forward.TryGetValue(p.S1, out to)) { to = new HashSet <State>(); forward[p.S1] = to; } to.Add(p.S2); HashSet <State> from; if (!back.TryGetValue(p.S2, out from)) { from = new HashSet <State>(); back[p.S2] = from; } from.Add(p.S1); } // calculate epsilon closure LinkedList <StatePair> worklist = new LinkedList <StatePair>(pairs); HashSet <StatePair> workset = new HashSet <StatePair>(pairs); while (worklist.Count > 0) { StatePair p = worklist.First.Value; worklist.Remove(p); workset.Remove(p); HashSet <State> to; HashSet <State> from; if (forward.TryGetValue(p.S2, out to)) { foreach (State s in to) { StatePair pp = new StatePair(p.S1, s); if (!pairs.Contains(pp)) { pairs.Add(pp); forward[p.S1].Add(s); back[s].Add(p.S1); worklist.AddLast(pp); workset.Add(pp); if (back.TryGetValue(p.S1, out from)) { foreach (State q in from) { StatePair qq = new StatePair(q, p.S1); if (!workset.Contains(qq)) { worklist.AddLast(qq); workset.Add(qq); } } } } } } } // add transitions foreach (StatePair p in pairs) { p.S1.AddEpsilon(p.S2); } a.deterministic = false; //a.clearHashCode(); a.ClearNumberedStates(); a.CheckMinimizeAlways(); }
public void RemoveByIndexShouldThrowInvalidOperationExceptionWhenEmpty() { Assert.Throws <InvalidOperationException>(() => CharList.Remove(0)); }
static void Main(string[] args) { LinkedList <Pictures <string> > list1 = new LinkedList <Pictures <string> >(); Pictures <string> img1 = new Pictures <string>("img1", ".jpg"); Pictures <string> img2 = new Pictures <string>("img2", ".png"); Pictures <string> img3 = new Pictures <string>("img3", ".svg"); Pictures <string> img4 = new Pictures <string>("img4", ".psd"); Pictures <string> img5 = new Pictures <string>("img5", ".jpg"); Pictures <string> img6 = new Pictures <string>("img6", ".png"); //доабвление разными способами list1.AddFirst(img1); list1.AddAfter(list1.Last, img2); list1.AddAfter(list1.Last, img3); list1.AddAfter(list1.Last, img4); list1.AddLast(img6); list1.AddBefore(list1.Last, img5); Console.WriteLine("Изначальная коллекция:"); //a. Выведите коллекцию на консоль foreach (Pictures <string> i in list1) { Console.WriteLine(i); } //удаление list1.Remove(img6); Console.WriteLine("Удаляем 1 элемент:"); foreach (Pictures <string> i in list1) { Console.WriteLine(i); } //b. Удалите из коллекции n последовательных элементов for (int i = 1; i < 3; i++) { list1.Remove(list1.ElementAt(2)); } Console.WriteLine("Удаляем несколько последовательных:"); foreach (Pictures <string> i in list1) { Console.WriteLine(i); } //. Создайте вторую коллекцию List <Pictures <string> > list2 = new List <Pictures <string> >(); foreach (Pictures <string> i in list1) /////запись элементов второй коллекции в третью { list2.Add(i); } Console.WriteLine("Запись эллементов во вторую коллекцию:"); foreach (var i in list2) { Console.WriteLine(i); } Console.WriteLine("Поиск эллемента по значению поля:"); var item = list2.Find(o => o.Name == "img2"); Console.WriteLine(item); ObservableCollection <Pictures <string> > obs = new ObservableCollection <Pictures <string> >(); obs.CollectionChanged += StaticClass.Method; obs.Add(img1); obs.Add(img2); obs.Add(img3); obs.Add(img4); obs.Add(img5); obs.Add(img6); obs.Remove(img3); obs.Remove(img5); Console.WriteLine("Конечная просматриваемая коллекция: "); foreach (var i in obs) { Console.WriteLine(i); } Console.ReadKey(); }
void RemovePlacemat(Placemat placemat) { placemat.RemoveFromHierarchy(); m_Placemats.Remove(placemat); }
protected override bool TryDequeue(Task task) { lock (_tasks) return(_tasks.Remove(task)); }
public void Remove(ICommand command) { m_CommandList.Remove(command); }
public void Remove(T obj) { listic.Remove(obj); }
public static void Main(string[] args) { int number = 5000; LinkedList <LinkedList <int> > items = new LinkedList <LinkedList <int> >(); //LinkedList<int> items = new LinkedList<int>(); int[] n = Console.ReadLine().Split().Select(x => int.Parse(x)).ToArray(); LinkedList <int> group = new LinkedList <int>(); for (int i = 0; i < n[0]; i++) { if (i % number == 0) { group = new LinkedList <int>(); items.Add(group); items.SaveCursor(); items.MovePrev(); items.Value?.ResetCursor(); items.LoadCursor(); } group.Add(i + 1); } Stopwatch watch = new Stopwatch(); watch.Start(); int count = n[1]; List <int> ans = new List <int>(); items.MoveStart(); int tempCount = count; while (items.IsEmpty is false) { while (tempCount > 0) { if (tempCount <= items.Value.Count) { break; } tempCount -= items.Value.Count; items.MoveNext(); items.Value.ResetCursor(); } group = items.Value; group.MoveNext(count % number); ans.Add(group.Value); group.Remove(); var tempGroup = group; items.SaveCursor(); int shiftCount = 0; while (items.MoveNext()) { tempGroup.MoveEnd(); items.Value.MoveStart(); shiftCount++; for (int i = 0; i < shiftCount; i++) { tempGroup.Add(items.Value.Value); items.Value.Remove(); items.Value.MoveStart(); if (items.Value.IsEmpty) { items.Remove(); //items.MoveEnd(); break; } } tempGroup = items.Value; } items.LoadCursor(); if (items.Value.IsEmpty) { items.Remove(); items.MoveStart(); } tempCount = count - (group.Count - count % number); } Console.WriteLine($"<{string.Join(", ", ans)}>"); // watch.Stop(); // Console.WriteLine(watch.Elapsed.TotalSeconds); }
public virtual void OnUnregisterTask(ITask task) { m_SceneTask.Remove(task); }
/// <summary> /// Returns true if the language of <paramref name="a1"/> is a subset of the language /// of <paramref name="a2"/>. As a side-effect, <paramref name="a2"/> is determinized if /// not already marked as deterministic. /// <para/> /// Complexity: quadratic in number of states. /// </summary> public static bool SubsetOf(Automaton a1, Automaton a2) { if (a1 == a2) { return(true); } if (a1.IsSingleton) { if (a2.IsSingleton) { return(a1.singleton.Equals(a2.singleton, StringComparison.Ordinal)); } return(BasicOperations.Run(a2, a1.singleton)); } a2.Determinize(); Transition[][] transitions1 = a1.GetSortedTransitions(); Transition[][] transitions2 = a2.GetSortedTransitions(); LinkedList <StatePair> worklist = new LinkedList <StatePair>(); HashSet <StatePair> visited = new HashSet <StatePair>(); StatePair p = new StatePair(a1.initial, a2.initial); worklist.AddLast(p); visited.Add(p); while (worklist.Count > 0) { p = worklist.First.Value; worklist.Remove(p); if (p.S1.accept && !p.S2.accept) { return(false); } Transition[] t1 = transitions1[p.S1.number]; Transition[] t2 = transitions2[p.S2.number]; for (int n1 = 0, b2 = 0; n1 < t1.Length; n1++) { while (b2 < t2.Length && t2[b2].max < t1[n1].min) { b2++; } int min1 = t1[n1].min, max1 = t1[n1].max; for (int n2 = b2; n2 < t2.Length && t1[n1].max >= t2[n2].min; n2++) { if (t2[n2].min > min1) { return(false); } if (t2[n2].max < Character.MAX_CODE_POINT) { min1 = t2[n2].max + 1; } else { min1 = Character.MAX_CODE_POINT; max1 = Character.MIN_CODE_POINT; } StatePair q = new StatePair(t1[n1].to, t2[n2].to); if (!visited.Contains(q)) { worklist.AddLast(q); visited.Add(q); } } if (min1 <= max1) { return(false); } } } return(true); }
/// <summary> /// Determinizes the given automaton. /// <para/> /// Worst case complexity: exponential in number of states. /// </summary> public static void Determinize(Automaton a) { if (a.IsDeterministic || a.IsSingleton) { return; } State[] allStates = a.GetNumberedStates(); // subset construction bool initAccept = a.initial.accept; int initNumber = a.initial.number; a.initial = new State(); SortedInt32Set.FrozenInt32Set initialset = new SortedInt32Set.FrozenInt32Set(initNumber, a.initial); LinkedList <SortedInt32Set.FrozenInt32Set> worklist = new LinkedList <SortedInt32Set.FrozenInt32Set>(); IDictionary <SortedInt32Set.FrozenInt32Set, State> newstate = new Dictionary <SortedInt32Set.FrozenInt32Set, State>(); worklist.AddLast(initialset); a.initial.accept = initAccept; newstate[initialset] = a.initial; int newStateUpto = 0; State[] newStatesArray = new State[5]; newStatesArray[newStateUpto] = a.initial; a.initial.number = newStateUpto; newStateUpto++; // like Set<Integer,PointTransitions> PointTransitionSet points = new PointTransitionSet(); // like SortedMap<Integer,Integer> SortedInt32Set statesSet = new SortedInt32Set(5); // LUCENENET NOTE: The problem here is almost certainly // due to the conversion to FrozenIntSet along with its // differing equality checking. while (worklist.Count > 0) { SortedInt32Set.FrozenInt32Set s = worklist.First.Value; worklist.Remove(s); // Collate all outgoing transitions by min/1+max: for (int i = 0; i < s.values.Length; i++) { State s0 = allStates[s.values[i]]; for (int j = 0; j < s0.numTransitions; j++) { points.Add(s0.TransitionsArray[j]); } } if (points.count == 0) { // No outgoing transitions -- skip it continue; } points.Sort(); int lastPoint = -1; int accCount = 0; State r = s.state; for (int i = 0; i < points.count; i++) { int point = points.points[i].point; if (statesSet.upto > 0) { Debug.Assert(lastPoint != -1); statesSet.ComputeHash(); State q; if (!newstate.TryGetValue(statesSet.ToFrozenInt32Set(), out q) || q == null) { q = new State(); SortedInt32Set.FrozenInt32Set p = statesSet.Freeze(q); worklist.AddLast(p); if (newStateUpto == newStatesArray.Length) { State[] newArray = new State[ArrayUtil.Oversize(1 + newStateUpto, RamUsageEstimator.NUM_BYTES_OBJECT_REF)]; Array.Copy(newStatesArray, 0, newArray, 0, newStateUpto); newStatesArray = newArray; } newStatesArray[newStateUpto] = q; q.number = newStateUpto; newStateUpto++; q.accept = accCount > 0; newstate[p] = q; } else { Debug.Assert((accCount > 0) == q.accept, "accCount=" + accCount + " vs existing accept=" + q.accept + " states=" + statesSet); } r.AddTransition(new Transition(lastPoint, point - 1, q)); } // process transitions that end on this point // (closes an overlapping interval) Transition[] transitions = points.points[i].ends.transitions; int limit = points.points[i].ends.count; for (int j = 0; j < limit; j++) { Transition t = transitions[j]; int num = t.to.number; statesSet.Decr(num); accCount -= t.to.accept ? 1 : 0; } points.points[i].ends.count = 0; // process transitions that start on this point // (opens a new interval) transitions = points.points[i].starts.transitions; limit = points.points[i].starts.count; for (int j = 0; j < limit; j++) { Transition t = transitions[j]; int num = t.to.number; statesSet.Incr(num); accCount += t.to.accept ? 1 : 0; } lastPoint = point; points.points[i].starts.count = 0; } points.Reset(); Debug.Assert(statesSet.upto == 0, "upto=" + statesSet.upto); } a.deterministic = true; a.SetNumberedStates(newStatesArray, newStateUpto); }
private static void WriteProductsData(LinkedList <Product> products) { const string books = "1. Книги"; const string programmingBooks = "1.1. Книги по программированию"; const string cookeryBooks = "1.2. Книги по кулинарии"; const string esotericsBooks = "1.3. Книги по эзотерике"; const string discs = "2. Диски"; const string discsCd = "2.1. CD-диски"; const string discsDvd = "2.2. DVD-диски"; const string discsCdMusic = "2.1.1. CD-диски c музыкой"; const string discsCdVideo = "2.1.2. CD-диски c видео"; const string discsCdSoftware = "2.1.3. CD-диски c ПО"; const string discsDvdMusic = "2.2.1. DVD-диски c музыкой"; const string discsDvdVideo = "2.2.2. DVD-диски c видео"; const string discsDvdSoftware = "2.2.3. DVD-диски c ПО"; Console.WriteLine(books); #region books data writing Console.WriteLine(programmingBooks); for (var i = 0; i < products.Count; i++) { if (products.ElementAt(i).GetType() == typeof(ProgrammingBook)) { Console.WriteLine(products.ElementAt(i).GetData()); Console.WriteLine(); products.Remove(products.ElementAt(i)); } } Console.WriteLine(cookeryBooks); for (var i = 0; i < products.Count; i++) { if (products.ElementAt(i).GetType() == typeof(CookeryBook)) { Console.WriteLine(products.ElementAt(i).GetData()); Console.WriteLine(); products.Remove(products.ElementAt(i)); } } Console.WriteLine(esotericsBooks); for (var i = 0; i < products.Count; i++) { if (products.ElementAt(i).GetType() == typeof(EsotericsBook)) { Console.WriteLine(products.ElementAt(i).GetData()); Console.WriteLine(); products.Remove(products.ElementAt(i)); } } #endregion Console.WriteLine(discs); Console.WriteLine(discsCd); #region cd discs data writing Console.WriteLine(discsCdMusic); for (var i = 0; i < products.Count; i++) { if (products.ElementAt(i).GetType() == typeof(Disc) && ((Disc)products.ElementAt(i)).DiscType == Disc.DiscTypeCd && ((Disc)products.ElementAt(i)).DiscContentType == Disc.DiscContentTypeMusic) { Console.WriteLine(products.ElementAt(i).GetData()); Console.WriteLine(); products.Remove(products.ElementAt(i)); } } Console.WriteLine(discsCdVideo); for (var i = 0; i < products.Count; i++) { if (products.ElementAt(i).GetType() == typeof(Disc) && ((Disc)products.ElementAt(i)).DiscType == Disc.DiscTypeCd && ((Disc)products.ElementAt(i)).DiscContentType == Disc.DiscContentTypeVideo) { Console.WriteLine(products.ElementAt(i).GetData()); Console.WriteLine(); products.Remove(products.ElementAt(i)); } } Console.WriteLine(discsCdSoftware); for (var i = 0; i < products.Count; i++) { if (products.ElementAt(i).GetType() == typeof(Disc) && ((Disc)products.ElementAt(i)).DiscType == Disc.DiscTypeCd && ((Disc)products.ElementAt(i)).DiscContentType == Disc.DiscContentTypeSoftware) { Console.WriteLine(products.ElementAt(i).GetData()); Console.WriteLine(); products.Remove(products.ElementAt(i)); } } #endregion Console.WriteLine(discsDvd); #region dvd discs data writing Console.WriteLine(discsDvdMusic); for (var i = 0; i < products.Count; i++) { if (products.ElementAt(i).GetType() == typeof(Disc) && ((Disc)products.ElementAt(i)).DiscType == Disc.DiscTypeDvd && ((Disc)products.ElementAt(i)).DiscContentType == Disc.DiscContentTypeMusic) { Console.WriteLine(products.ElementAt(i).GetData()); Console.WriteLine(); products.Remove(products.ElementAt(i)); } } Console.WriteLine(discsDvdVideo); for (var i = 0; i < products.Count; i++) { if (products.ElementAt(i).GetType() == typeof(Disc) && ((Disc)products.ElementAt(i)).DiscType == Disc.DiscTypeDvd && ((Disc)products.ElementAt(i)).DiscContentType == Disc.DiscContentTypeVideo) { Console.WriteLine(products.ElementAt(i).GetData()); Console.WriteLine(); products.Remove(products.ElementAt(i)); } } Console.WriteLine(discsDvdSoftware); for (var i = 0; i < products.Count; i++) { if (products.ElementAt(i).GetType() == typeof(Disc) && ((Disc)products.ElementAt(i)).DiscType == Disc.DiscTypeDvd && ((Disc)products.ElementAt(i)).DiscContentType == Disc.DiscContentTypeSoftware) { Console.WriteLine(products.ElementAt(i).GetData()); Console.WriteLine(); products.Remove(products.ElementAt(i)); } } #endregion }
/// <summary> /// Returns an automaton that accepts the intersection of the languages of the /// given automata. Never modifies the input automata languages. /// <para/> /// Complexity: quadratic in number of states. /// </summary> public static Automaton Intersection(Automaton a1, Automaton a2) { if (a1.IsSingleton) { if (BasicOperations.Run(a2, a1.singleton)) { return(a1.CloneIfRequired()); } else { return(BasicAutomata.MakeEmpty()); } } if (a2.IsSingleton) { if (BasicOperations.Run(a1, a2.singleton)) { return(a2.CloneIfRequired()); } else { return(BasicAutomata.MakeEmpty()); } } if (a1 == a2) { return(a1.CloneIfRequired()); } Transition[][] transitions1 = a1.GetSortedTransitions(); Transition[][] transitions2 = a2.GetSortedTransitions(); Automaton c = new Automaton(); LinkedList <StatePair> worklist = new LinkedList <StatePair>(); Dictionary <StatePair, StatePair> newstates = new Dictionary <StatePair, StatePair>(); StatePair p = new StatePair(c.initial, a1.initial, a2.initial); worklist.AddLast(p); newstates[p] = p; while (worklist.Count > 0) { p = worklist.First.Value; worklist.Remove(p); p.s.accept = p.S1.accept && p.S2.accept; Transition[] t1 = transitions1[p.S1.number]; Transition[] t2 = transitions2[p.S2.number]; for (int n1 = 0, b2 = 0; n1 < t1.Length; n1++) { while (b2 < t2.Length && t2[b2].max < t1[n1].min) { b2++; } for (int n2 = b2; n2 < t2.Length && t1[n1].max >= t2[n2].min; n2++) { if (t2[n2].max >= t1[n1].min) { StatePair q = new StatePair(t1[n1].to, t2[n2].to); StatePair r; newstates.TryGetValue(q, out r); if (r == null) { q.s = new State(); worklist.AddLast(q); newstates[q] = q; r = q; } int min = t1[n1].min > t2[n2].min ? t1[n1].min : t2[n2].min; int max = t1[n1].max < t2[n2].max ? t1[n1].max : t2[n2].max; p.s.AddTransition(new Transition(min, max, r.s)); } } } } c.deterministic = a1.deterministic && a2.deterministic; c.RemoveDeadTransitions(); c.CheckMinimizeAlways(); return(c); }
public override bool IncrementToken() { for (;;) { if (!(remainingTokens.Count == 0)) { // clearAttributes(); // not currently necessary var first = remainingTokens.First; remainingTokens.Remove(first); RestoreState(first.Value); return(true); } if (!m_input.IncrementToken()) { return(false); } int len = termAtt.Length; if (len == 0) { return(true); // pass through zero length terms } int firstAlternativeIncrement = inject ? 0 : posAtt.PositionIncrement; string v = termAtt.ToString(); string primaryPhoneticValue = encoder.GetDoubleMetaphone(v); string alternatePhoneticValue = encoder.GetDoubleMetaphone(v, true); // a flag to lazily save state if needed... this avoids a save/restore when only // one token will be generated. bool saveState = inject; if (primaryPhoneticValue != null && primaryPhoneticValue.Length > 0 && !primaryPhoneticValue.Equals(v)) { if (saveState) { remainingTokens.AddLast(CaptureState()); } posAtt.PositionIncrement = firstAlternativeIncrement; firstAlternativeIncrement = 0; termAtt.SetEmpty().Append(primaryPhoneticValue); saveState = true; } if (alternatePhoneticValue != null && alternatePhoneticValue.Length > 0 && !alternatePhoneticValue.Equals(primaryPhoneticValue) && !primaryPhoneticValue.Equals(v)) { if (saveState) { remainingTokens.AddLast(CaptureState()); saveState = false; } posAtt.PositionIncrement = firstAlternativeIncrement; termAtt.SetEmpty().Append(alternatePhoneticValue); saveState = true; } // Just one token to return, so no need to capture/restore // any state, simply return it. if (remainingTokens.Count == 0) { return(true); } if (saveState) { remainingTokens.AddLast(CaptureState()); } } }
public static void Show() { //1 内存连续存储,节约空间,可以索引访问,读取快,增删慢 #region Array { //Array:在内存上连续分配的,而且元素类型是一样的 //可以坐标访问 读取快--增删慢,长度不变 Console.WriteLine("***************Array******************"); int[] intArray = new int[3]; intArray[0] = 123; string[] stringArray = new string[] { "123", "234" };//Array } { //ArrayList 不定长的,连续分配的; //元素没有类型限制,任何元素都是当成object处理,如果是值类型,会有装箱操作 //读取快--增删慢 Console.WriteLine("***************ArrayList******************"); ArrayList arrayList = new ArrayList(); arrayList.Add("Eleven"); arrayList.Add("Is"); arrayList.Add(32);//add增加长度 //arrayList[4] = 26;//索引复制,不会增加长度 //删除数据 //arrayList.RemoveAt(4); var value = arrayList[2]; arrayList.RemoveAt(0); arrayList.Remove("Eleven"); } { //List:也是Array,内存上都是连续摆放;不定长;泛型,保证类型安全,避免装箱拆箱 //读取快--增删慢 Console.WriteLine("***************List<T>******************"); List <int> intList = new List <int>() { 1, 2, 3, 4 }; intList.Add(123); intList.Add(123); //intList.Add("123"); //intList[0] = 123; List <string> stringList = new List <string>(); //stringList[0] = "123";//异常的 foreach (var item in intList) { } } #endregion //2 非连续摆放,存储数据+地址,找数据的话就只能顺序查找,读取慢;增删快, #region 链表 { //LinkedList:泛型的特点;链表,元素不连续分配,每个元素都有记录前后节点 //节点值可以重复 //能不能下标访问?不能,找元素就只能遍历 查找不方便 //增删 就比较方便 Console.WriteLine("***************LinkedList<T>******************"); LinkedList <int> linkedList = new LinkedList <int>(); //linkedList[3] linkedList.AddFirst(123); linkedList.AddLast(456); bool isContain = linkedList.Contains(123); LinkedListNode <int> node123 = linkedList.Find(123); //元素123的位置 从头查找 linkedList.AddBefore(node123, 123); linkedList.AddBefore(node123, 123); linkedList.AddAfter(node123, 9); linkedList.Remove(456); linkedList.Remove(node123); linkedList.RemoveFirst(); linkedList.RemoveLast(); linkedList.Clear(); } { //Queue 就是链表 先进先出 放任务延迟执行,A不断写入日志任务 B不断获取任务去执行 Console.WriteLine("***************Queue<T>******************"); Queue <string> numbers = new Queue <string>(); numbers.Enqueue("one"); numbers.Enqueue("two"); numbers.Enqueue("three"); numbers.Enqueue("four"); numbers.Enqueue("four"); numbers.Enqueue("five"); foreach (string number in numbers) { Console.WriteLine(number); } Console.WriteLine($"Dequeuing '{numbers.Dequeue()}'"); Console.WriteLine($"Peek at next item to dequeue: { numbers.Peek()}"); Console.WriteLine($"Dequeuing '{numbers.Dequeue()}'"); Queue <string> queueCopy = new Queue <string>(numbers.ToArray()); foreach (string number in queueCopy) { Console.WriteLine(number); } Console.WriteLine($"queueCopy.Contains(\"four\") = {queueCopy.Contains("four")}"); queueCopy.Clear(); Console.WriteLine($"queueCopy.Count = {queueCopy.Count}"); } //队列是没瓶底的瓶子,栈是有瓶底的瓶子 { //Stack 就是链表 先进后出 解析表达式目录树的时候,先产生的数据后使用 //操作记录为命令,撤销的时候是倒序的 Console.WriteLine("***************Stack<T>******************"); Stack <string> numbers = new Stack <string>(); numbers.Push("one"); numbers.Push("two"); numbers.Push("three"); numbers.Push("four"); numbers.Push("five");//放进去 foreach (string number in numbers) { Console.WriteLine(number); } Console.WriteLine($"Pop '{numbers.Pop()}'"); //获取并移除 Console.WriteLine($"Peek at next item to dequeue: { numbers.Peek()}"); //获取不移除 Console.WriteLine($"Pop '{numbers.Pop()}'"); Stack <string> stackCopy = new Stack <string>(numbers.ToArray()); foreach (string number in stackCopy) { Console.WriteLine(number); } Console.WriteLine($"stackCopy.Contains(\"four\") = {stackCopy.Contains("four")}"); stackCopy.Clear(); Console.WriteLine($"stackCopy.Count = {stackCopy.Count}"); } #endregion //set纯粹的集合,容器,东西丢进去,唯一性 无序的 #region Set { //集合:hash分布,元素间没关系,动态增加容量 去重 //统计用户IP;IP投票 交叉并补--二次好友/间接关注/粉丝合集 Console.WriteLine("***************HashSet<string>******************"); HashSet <string> hashSet = new HashSet <string>(); hashSet.Add("123"); hashSet.Add("689"); hashSet.Add("456"); hashSet.Add("12435"); hashSet.Add("12435"); hashSet.Add("12435"); //hashSet[0]; foreach (var item in hashSet) { Console.WriteLine(item); } Console.WriteLine(hashSet.Count); Console.WriteLine(hashSet.Contains("12345")); { HashSet <string> hashSet1 = new HashSet <string>(); hashSet1.Add("123"); hashSet1.Add("689"); hashSet1.Add("789"); hashSet1.Add("12435"); hashSet1.Add("12435"); hashSet1.Add("12435"); hashSet1.SymmetricExceptWith(hashSet); //补 hashSet1.UnionWith(hashSet); //并 hashSet1.ExceptWith(hashSet); //差 hashSet1.IntersectWith(hashSet); //交 //风--亡五 找出共同的好友 } hashSet.ToList(); hashSet.Clear(); } { //排序的集合:去重 而且排序 //统计排名--每统计一个就丢进去集合 Console.WriteLine("***************SortedSet<string>******************"); SortedSet <string> sortedSet = new SortedSet <string>(); //IComparer<T> comparer 自定义对象要排序,就用这个指定 sortedSet.Add("123"); sortedSet.Add("689"); sortedSet.Add("456"); sortedSet.Add("12435"); sortedSet.Add("12435"); sortedSet.Add("12435"); foreach (var item in sortedSet) { Console.WriteLine(item); } Console.WriteLine(sortedSet.Count); Console.WriteLine(sortedSet.Contains("12345")); { SortedSet <string> sortedSet1 = new SortedSet <string>(); sortedSet1.Add("123"); sortedSet1.Add("689"); sortedSet1.Add("456"); sortedSet1.Add("12435"); sortedSet1.Add("12435"); sortedSet1.Add("12435"); sortedSet1.SymmetricExceptWith(sortedSet); //补 sortedSet1.UnionWith(sortedSet); //并 sortedSet1.ExceptWith(sortedSet); //差 sortedSet1.IntersectWith(sortedSet); //交 } sortedSet.ToList(); sortedSet.Clear(); } #endregion //读取&增删都快? 有 hash散列 字典 //key-value,一段连续有限空间放value(开辟的空间比用到的多,hash是用空间换性能),基于key散列计算得到地址索引,这样读取快 //增删也快,删除时也是计算位置,增加也不影响别人 //肯定会出现2个key(散列冲突),散列结果一致18,可以让第二次的+1, //可能会造成效率的降低,尤其是数据量大的情况下,以前测试过dictionary在3w条左右性能就开始下降的厉害 #region key-value { //Hashtable key-value 体积可以动态增加 拿着key计算一个地址,然后放入key - value //object-装箱拆箱 如果不同的key得到相同的地址,第二个在前面地址上 + 1 //查找的时候,如果地址对应数据的key不对,那就 + 1查找。。 //浪费了空间,Hashtable是基于数组实现 //查找个数据 一次定位; 增删 一次定位; 增删查改 都很快 //浪费空间,数据太多,重复定位定位,效率就下去了 Console.WriteLine("***************Hashtable******************"); Hashtable table = new Hashtable(); table.Add("123", "456"); table[234] = 456; table[234] = 567; table[32] = 4562; table[1] = 456; table["eleven"] = 456; foreach (DictionaryEntry objDE in table) { Console.WriteLine(objDE.Key.ToString()); Console.WriteLine(objDE.Value.ToString()); } //线程安全 Hashtable.Synchronized(table);//只有一个线程写 多个线程读 } { //字典:泛型;key - value,增删查改 都很快;有序的 // 字典不是线程安全 ConcurrentDictionary Console.WriteLine("***************Dictionary******************"); Dictionary <int, string> dic = new Dictionary <int, string>(); dic.Add(1, "HaHa"); dic.Add(5, "HoHo"); dic.Add(3, "HeHe"); dic.Add(2, "HiHi"); dic.Add(4, "HuHu1"); dic[4] = "HuHu"; dic.Add(4, "HuHu"); foreach (var item in dic) { Console.WriteLine($"Key:{item.Key}, Value:{item.Value}"); } } { Console.WriteLine("***************SortedDictionary******************"); SortedDictionary <int, string> dic = new SortedDictionary <int, string>(); dic.Add(1, "HaHa"); dic.Add(5, "HoHo"); dic.Add(3, "HeHe"); dic.Add(2, "HiHi"); dic.Add(4, "HuHu1"); dic[4] = "HuHu"; dic.Add(4, "HuHu"); foreach (var item in dic) { Console.WriteLine($"Key:{item.Key}, Value:{item.Value}"); } } { //"a".GetHashCode(); Console.WriteLine("***************SortedList******************"); SortedList sortedList = new SortedList();//IComparer sortedList.Add("First", "Hello"); sortedList.Add("Second", "World"); sortedList.Add("Third", "!"); sortedList["Third"] = "~~"; // sortedList.Add("Fourth", "!"); sortedList.Add("Fourth", "!"); //重复的Key Add会错 sortedList["Fourth"] = "!!!"; var keyList = sortedList.GetKeyList(); var valueList = sortedList.GetValueList(); sortedList.TrimToSize();//用于最小化集合的内存开销 sortedList.Remove("Third"); sortedList.RemoveAt(0); sortedList.Clear(); } #endregion { //ConcurrentQueue 线程安全版本的Queue //ConcurrentStack线程安全版本的Stack //ConcurrentBag线程安全的对象集合 //ConcurrentDictionary线程安全的Dictionary //BlockingCollection } { List <string> fruits = new List <string> { "apple", "passionfruit", "banana", "mango", "orange", "blueberry", "grape", "strawberry" }; IEnumerable <string> query = fruits.Where(fruit => fruit.Length < 6); foreach (var item in query)//遍历才会去查询比较 迭代器 yield { } IQueryable <string> queryable = fruits.AsQueryable <string>().Where(s => s.Length > 5); foreach (var item in queryable)//表达式目录树的解析,延迟到遍历的时候才去执行 EF的延迟查询 { } } }
// 2.3 Implement an algorithm to delete a node in the middle of a single linked list, given only access to that node. public static LinkedList <T> RemoveNode <T>(LinkedList <T> list, LinkedListNode <T> node) { list.Remove(node); return(list); }
public void removeWidget(WidgetModel w) { widgets.Remove(w); }
internal List <LogForwarder>?Log(LogMessage logMessage) { lock (_mutex) { List <LogForwarder>?logForwarderList = null; // Put message in _queue if ((logMessage.Type != LogMessageType.TraceMessage && _maxLogCount > 0) || (logMessage.Type == LogMessageType.TraceMessage && _maxTraceCount > 0)) { _queue.AddLast(logMessage); if (logMessage.Type != LogMessageType.TraceMessage) { Debug.Assert(_maxLogCount > 0); if (_logCount == _maxLogCount) { // Need to remove the oldest log from the queue Debug.Assert(_oldestLog != null); LinkedListNode <LogMessage>?next = _oldestLog.Next; _queue.Remove(_oldestLog); _oldestLog = next; while (_oldestLog != null && _oldestLog.Value.Type == LogMessageType.TraceMessage) { _oldestLog = _oldestLog.Next; } Debug.Assert(_oldestLog != null); // remember: we just added a Log at the end } else { Debug.Assert(_logCount < _maxLogCount); _logCount++; if (_oldestLog == null) { _oldestLog = _queue.Last; } } } else { Debug.Assert(_maxTraceCount > 0); if (_traceCount == _maxTraceCount) { // Need to remove the oldest trace from the queue Debug.Assert(_oldestTrace != null); LinkedListNode <LogMessage>?next = _oldestTrace.Next; _queue.Remove(_oldestTrace); _oldestTrace = next; while (_oldestTrace != null && _oldestTrace.Value.Type != LogMessageType.TraceMessage) { _oldestTrace = _oldestTrace.Next; } Debug.Assert(_oldestTrace != null); // remember: we just added a Log at the end } else { Debug.Assert(_traceCount < _maxTraceCount); _traceCount++; if (_oldestTrace == null) { _oldestTrace = _queue.Last; } } } } // Queue updated, now find which remote loggers want this message foreach (LogForwarder p in _logForwarderMap.Values) { if (p.IsAccepted(logMessage)) { logForwarderList ??= new List <LogForwarder>(); logForwarderList.Add(p); } } return(logForwarderList); } }
public void UnRegister(INPC enemy) { enemies.Remove(enemy); }
public void RemoveItem(Vector3 coord) { list.Remove(coord); }
internal void RemoveFloatingForm(FloatingViewForm floatingViewForm) { Verify.Argument.IsNotNull(floatingViewForm, nameof(floatingViewForm)); _floatingViewForms.Remove(floatingViewForm); }
public void RemoveItem(ListViewerItem item) { itemList.Remove(item); item.Destroy(); }
public bool Remove(T item) { LinkedList <T> bin = GetBin(item); return(this.spatialObjects.Remove(item) && bin.Remove(item)); }
public void Erase(T t) { //不是很高效 list.Remove(t); }
public async Task <TItem> GetAsync(TKey key, Func <TKey, Task <TItem> > on_miss, Action <TKey, TItem>?on_hit = null) { // Special case 0 capacity caches if (Capacity == 0) { return(await on_miss(key)); } TItem item; // Use the lookup map to find the node in the cache LinkedListNode <Entry> node; bool found = false; using (Lock()) found = m_lookup.TryGetValue(key, out node !); if (found) { // Found! Interlocked.Increment(ref m_stats.Hits); // For standard caches, move the item to the head of the cache list. // For object pools, remove the item from the cache before returning it. using (Lock()) { switch (Mode) { default: throw new Exception("Unknown cache mode"); case CacheMode.StandardCache: m_cache.Remove(node); m_cache.AddFirst(node); break; case CacheMode.ObjectPool: DeleteCachedItem(node, false); break; } } // Allow callers to do something on a cache hit on_hit?.Invoke(key, node.Value.Item); // Get the item to return item = node.Value.Item; } else { // Not found Interlocked.Increment(ref m_stats.Misses); // Cache miss, read it item = await on_miss(key); if (Equals(item, default(TItem) !)) { return(item); } // For standard caches, store the new item in the cache before returning it. // For object pools, do nothing, the user will put it in the cache when finished with it. switch (Mode) { default: throw new Exception("Unknown cache mode"); case CacheMode.StandardCache: using (Lock()) { // Check again if 'key' is not in the cache, it might have been // added by another thread while we weren't holding the lock. if (!m_lookup.TryGetValue(key, out node !)) { // Create a new node and add to the cache node = m_cache.AddFirst(new Entry(key, item)); m_lookup[key] = node; LimitCacheSize(); } // Get the item to return item = node.Value.Item; } break; case CacheMode.ObjectPool: break; // Return 'item' } } // Return the cached object. // For standard caches this item should really be immutable // For object pools, it doesn't matter because it's not in our cache now. return(item); }