// this is a no-allocation way to sum an int queue internal static int Sum(System.Collections.Generic.Queue<int> queue) { var value = 0; for (int i = 0; i < queue.Count; i++) { var temp = queue.Dequeue(); value += temp; queue.Enqueue(temp); } return value; }
protected override void TakeArguments(System.Collections.Generic.Queue<string> queue) { string typeRepresentation = queue.Dequeue(); ResolvedType = Type.GetType(typeRepresentation); }
protected override void TakeArguments(System.Collections.Generic.Queue<string> queue) { FileName = queue.Dequeue(); }
public void ShouldBeAbleToEnumerateContent() { var lookup = new Lookup<string> { { "key1", "value1.1" }, { "key1", "value1.2" }, { "key2", "value2.1" } }; lookup.Count().ShouldBe(2); var queue = new[] { new {key = "key1", values = new[] {"value1.1", "value1.2"}}, new {key = "key2", values = new[] {"value2.1"}}, }.ToQueue(); foreach (var grouping in lookup) { var expected = queue.Dequeue(); grouping.Key.ShouldBe(expected.key); grouping.AsEnumerable().ShouldBe(expected.values); } }
public async Task<Errorable<TreeNode>> PersistTree(TreeID rootid, ImmutableContainer<TreeID, TreeNode> trees) { if (trees == null) throw new ArgumentNullException("trees"); // TODO: better return value than `null` if (trees.Count == 0) return (TreeNode)null; // Start a query to check what Trees exist already: var existTrees = await db.ExecuteListQueryAsync(new QueryTreesExist(trees.Keys), expectedCapacity: trees.Count); // This code scans the tree breadth-first and builds a reversed depth-ordered stack: var reverseDepthOrder = new { id = rootid, depth = 0 }.StackOf(trees.Count); reverseDepthOrder.Pop(); var breadthFirstQueue = new { id = rootid, depth = 0 }.QueueOf(trees.Count); while (breadthFirstQueue.Count > 0) { var curr = breadthFirstQueue.Dequeue(); // Add it to the reverse stack: reverseDepthOrder.Push(curr); TreeNode node; if (!trees.TryGetValue(curr.id, out node)) { // TODO: didn't find the TreeID in the given collection, assume already persisted? continue; } // Queue up the child TreeIDs: foreach (var trtr in node.Trees) breadthFirstQueue.Enqueue(new { id = trtr.TreeID, depth = curr.depth + 1 }); } // This code takes the reverse depth-ordered stack and persists the tree nodes in groups per depth level. // This ensures that all child nodes across the breadth of the tree at each depth level are persisted // before moving up to their parents. List<Task<Errorable<TreeNode>>> persistTasks = new List<Task<Errorable<TreeNode>>>(); // Initialize the `isPersisting` set with the set of TreeIDs that already exist. HashSet<TreeID> isPersisting = new HashSet<TreeID>(existTrees); int lastDepth = reverseDepthOrder.Peek().depth; foreach (var curr in reverseDepthOrder) { Debug.WriteLine(String.Format("{0}: {1}", curr.depth, curr.id.ToString(firstLength: 7))); // An invariant of the algorithm, enforced via assert: Debug.Assert(curr.depth <= lastDepth); // Did we move to the next depth group: if ((persistTasks.Count > 0) && (curr.depth != lastDepth)) { Debug.WriteLine(String.Format("Awaiting depth group {0}...", lastDepth)); // Wait for the last depth group to finish persisting: await Task.WhenAll(persistTasks); // Start a new depth group: persistTasks = new List<Task<Errorable<TreeNode>>>(); } // Don't re-persist the same TreeID (this is a legit case - the same TreeID may be seen in different nodes of the tree): if (isPersisting.Contains(curr.id)) { Debug.WriteLine(String.Format("Already persisting {0}", curr.id.ToString(firstLength: 7))); // Keep track of the last depth level: lastDepth = curr.depth; continue; } // Get the TreeNode and persist it: TreeNode node = trees[curr.id]; isPersisting.Add(curr.id); // Fire up a task to persist this tree node: var tsk = db.ExecuteNonQueryAsync(new PersistTree(node)); // Add the task to the depth group to await: Debug.WriteLine(String.Format("Adding to depth group {0}...", curr.depth)); persistTasks.Add(tsk); // Keep track of the last depth level: lastDepth = curr.depth; } Debug.Assert(lastDepth == 0); if (persistTasks.Count > 0) { // Await the last group (the root node): Debug.WriteLine(String.Format("Awaiting depth group {0}...", lastDepth)); await Task.WhenAll(persistTasks); } // Return the root TreeNode: return trees[rootid]; }
public override object CalculateResult() { return new Range(NumGames) .AsParallel() .Select(x => { Random random = MathUtilities.CreateRandom(); var communityChestCards = new[] { CommunityChestCard.AdvanceToGo, CommunityChestCard.GoToJail, CommunityChestCard.Other, CommunityChestCard.Other, CommunityChestCard.Other, CommunityChestCard.Other, CommunityChestCard.Other, CommunityChestCard.Other, CommunityChestCard.Other, CommunityChestCard.Other, CommunityChestCard.Other, CommunityChestCard.Other, CommunityChestCard.Other, CommunityChestCard.Other, CommunityChestCard.Other, CommunityChestCard.Other, } .Shuffle(random) .ToQueue(); var chanceCards = new[] { ChanceCard.AdvanceToGo, ChanceCard.GoToJail, ChanceCard.GoToC1, ChanceCard.GoToE3, ChanceCard.GoToH2, ChanceCard.GoToRailroad1, ChanceCard.GoToNextRailroad, ChanceCard.GoToNextRailroad, ChanceCard.GoToNextUtility, ChanceCard.GoBackThreeSquares, ChanceCard.Other, ChanceCard.Other, ChanceCard.Other, ChanceCard.Other, ChanceCard.Other, ChanceCard.Other, } .Shuffle(random) .ToQueue(); Square currentPosition = Square.Go; Action refixPosition = () => { while (currentPosition < Square.Go) { currentPosition += BoardSize; } while (currentPosition > Square.H2) { currentPosition -= BoardSize; } }; DefaultDictionary<Square, int> landings = new DefaultDictionary<Square, int>(s => 0); for (int i = 0; i < NumTurnsPerGame; i++) { int numDoubles = 0; int die1 = random.Next(1, 1 + DieSize); int die2 = random.Next(1, 1 + DieSize); if (die1 == die2) { numDoubles++; } else { numDoubles = 0; } if (numDoubles == 3) { numDoubles = 0; currentPosition = Square.Jail; } else { currentPosition += die1 + die2; refixPosition(); checkPosition: if (currentPosition == Square.GoToJail) { currentPosition = Square.Jail; } else if (Chances.Contains(currentPosition)) { ChanceCard card = chanceCards.Dequeue(); chanceCards.Enqueue(card); switch (card) { case ChanceCard.AdvanceToGo: currentPosition = Square.Go; break; case ChanceCard.GoToJail: currentPosition = Square.GoToJail; break; case ChanceCard.GoToC1: currentPosition = Square.C1; break; case ChanceCard.GoToE3: currentPosition = Square.E3; break; case ChanceCard.GoToH2: currentPosition = Square.H2; break; case ChanceCard.GoToRailroad1: currentPosition = Square.Railroad1; break; case ChanceCard.GoToNextRailroad: while (!Railroads.Contains(currentPosition)) { currentPosition++; refixPosition(); } break; case ChanceCard.GoToNextUtility: while (!Utilities.Contains(currentPosition)) { currentPosition++; refixPosition(); } break; case ChanceCard.GoBackThreeSquares: currentPosition -= 3; refixPosition(); goto checkPosition; // I hate gotos, but it's the cleanest way in this case. } } else if (CommunityChests.Contains(currentPosition)) { CommunityChestCard card = communityChestCards.Dequeue(); communityChestCards.Enqueue(card); switch (card) { case CommunityChestCard.AdvanceToGo: currentPosition = Square.Go; break; case CommunityChestCard.GoToJail: currentPosition = Square.Jail; break; } } } landings[currentPosition]++; } return landings; }) .Aggregate((a, b) => { foreach (var pair in b) { if (!a.ContainsKey(pair.Key)) { a[pair.Key] = 0; } a[pair.Key] += pair.Value; } return a; }) .OrderByDescending(p => p.Value) .Select(p => p.Key) .Take(3) .Select(s => ((int)s).ToString("00")) .StringJoin(string.Empty); }
/* ------------------------------------- Private Methods ----------------------------------- */ /// <summary> Removes the first element. Returns null if no elements in queue. /// Always called with add_mutex locked (we don't have to lock add_mutex ourselves) /// </summary> protected object removeInternal(System.Collections.Queue queue) { object obj = null; lock (mutex) { int count = queue.Count; if (count > 0) { obj = queue.Dequeue(); } else { return null; } size--; if (size < 0) size = 0; if (peekInternal() == endMarker) closed = true; } return obj; }
protected override void TakeArguments(System.Collections.Generic.Queue<string> queue) { OutputFormat = queue.Dequeue().ToUpperInvariant(); }
private ScriptVariable ProcessData(System.Collections.Queue equation) { System.Collections.ArrayList tmpvars = new System.Collections.ArrayList(); ScriptVariable outv = new ScriptVariable(); outv.Type = Var_Types.ASSIGNABLE; ScriptVariable outi; System.Collections.Queue neweq = new System.Collections.Queue(); //lets process all the paran bullshit first while (equation.Count > 0) { string token1 = equation.Dequeue().ToString(); if (token1 == "(") { int pcnt = 1; System.Collections.Queue subeq = new System.Collections.Queue(); while (pcnt != 0) { string ntoken = equation.Dequeue().ToString(); if (ntoken == "(") { pcnt++; } if (ntoken == ")") { pcnt--; } if (pcnt != 0) { subeq.Enqueue(ntoken); } } outi = new ScriptVariable(); outi.Type = Var_Types.ASSIGNABLE; outi = ProcessData(subeq); outi.Name = Globals.SCRIPT_OUT_VAR + Globals.Rando.Next(int.MaxValue); while (VariableExists(outi.Name)) { outi.Name = Globals.SCRIPT_OUT_VAR + Globals.Rando.Next(int.MaxValue); } tmpvars.Add(outi.Name); Add_Variable(outi, StackHeight); neweq.Enqueue(outi.Name); } else { neweq.Enqueue(token1); } } //now we have a queue of pure tokens with no parans while (neweq.Count > 0) { string token1 = neweq.Dequeue().ToString(); if (neweq.Count == 0) { //we only had 1 parameter outv = Get_Var(token1); } else { outi = new ScriptVariable(); outi.Type = Var_Types.ASSIGNABLE; string token2 = neweq.Dequeue().ToString(); if (isUnaryOp(token1.ToUpperInvariant())) { EvaluateUnary(outi, token1.ToUpperInvariant(), token2); } else if (isBinaryOp(token2.ToUpperInvariant())) { string token3 = neweq.Dequeue().ToString(); EvaluateBinary(outi, token2.ToUpperInvariant(), token1, token3); } //add our created value to the stack outi.Name = Globals.SCRIPT_OUT_VAR + Globals.Rando.Next(int.MaxValue); while (VariableExists(outi.Name)) { outi.Name = Globals.SCRIPT_OUT_VAR + Globals.Rando.Next(int.MaxValue); } tmpvars.Add(outi.Name); Add_Variable(outi, StackHeight); //now we need to push this variable to the front of our queue via a temporary queue System.Collections.Queue tmpeq = new System.Collections.Queue(); tmpeq.Enqueue(outi.Name); while (neweq.Count > 0) { tmpeq.Enqueue(neweq.Dequeue()); } neweq = tmpeq; } } //delete all our temporary variables foreach (string name in tmpvars) { Script_DELETE(name); } return outv; }