static void Main(string[] args) { /* The words of the dictionary this evil hangman example works with are supplied in the linear array below. * For a more sophisticated implementation loading from an external file is obviously possible, but the idea here * was to provide a simple solution to the problem, so beginner programmers could understand how they could solve * it themselves. */ string[] dict = {"bakalava", "balamata", "balerina", "balirina", "baniceta", "kalotina", "kolibata", "korubata"}; HashSet<string> words = new HashSet<string>(dict); char[] seq = {'l', 'r', 'i', 'o', 'e', 'n', 'm', 'k', 'v', 't', 'b', 'c', 'd', 'f', 'g', 'h', 'j', 'p', 'r', 's', 'u', 'w', 'x', 'y', 'z'}; HashSet<char> toGuess = new HashSet<char>(seq); Random rand = new Random(); Console.WriteLine("Pick a word: (1-" + words.Count + ")"); int ind = int.Parse(Console.ReadLine()); Console.WriteLine("The word you chose is " + answer + ". Let's see whether the computer can guess it..."); answer = dict[ind - 1]; guessed.Add(answer[0]); guessed.Add(answer[answer.Length - 1]); while (words.Count != 1) { words.RemoveWhere(Remover); PrintGuessed(guessed); Console.WriteLine(string.Join(", ", words)); guessed.Add(toGuess.First()); toGuess.Remove(toGuess.First()); } Console.WriteLine("The word is: " + words.First()); Console.ReadLine(); }
public void Execute() { var mask = new NodeMask(); mask.Label = "Cycles"; mask.IsShowMask = true; try { if (!myPresentation.Graph.Nodes.Any()) { return; } var unvisited = new HashSet<Node>(myPresentation.Graph.Nodes); unvisited.RemoveWhere(n => n.In.Count == 0 || n.Out.Count == 0); while (unvisited.Count > 0) { var current = unvisited.First(); unvisited.Remove(current); foreach (var node in FindCycles(unvisited, current, new HashSet<Node> { current })) { mask.Set(node); } } } finally { var module = myPresentation.GetModule<INodeMaskModule>(); module.Push(mask); } }
public IEnumerable<State> TransitiveClosure ( Func<SimpleTransition, bool> selector, Func<SimpleTransition, bool> cancel) { var done = new HashSet<State> (); var work = new HashSet<State> (); work.Add (this); while (work.Any ()) { var q = work.First (); work.Remove (q); done.Add (q); if (q.Delta == null) { continue; } var ts = q.Delta .Where (t => selector == null || selector (t)) .ToArray (); if (cancel != null && ts.Any (cancel)) { return null; } foreach (var qn in ts.Select (t => t.Next)) { if (!done.Contains (qn)) { work.Add (qn); } } } return done; }
/// <summary> /// Find Longest Consequitive Sequence /// </summary> /// <param name="arr">Source Array</param> /// <returns>Length of longest consecutive numbers</returns> public static int LongestConsecutiveSequenceLength(int[] arr) { HashSet<int> allElements = new HashSet<int>(arr); int maxConsecutiveLength = 1; while (allElements.Count > 0) { int firstValue = allElements.First(); int leftElement = firstValue; int currentLength = 1; while (allElements.Contains(leftElement - 1)) { allElements.Remove(leftElement - 1); leftElement--; currentLength++; } int rightElement = firstValue; while (allElements.Contains(rightElement + 1)) { allElements.Remove(rightElement + 1); rightElement++; currentLength++; } if (currentLength > maxConsecutiveLength) { maxConsecutiveLength = currentLength; } allElements.Remove(firstValue); } return maxConsecutiveLength; }
// This method prints the guessed letters from the guessed hash and then reveals the guessed positionfs of the sought // word, whilst still keeping the non-guessed ones hidden. public static void PrintGuessed(HashSet<char> input) { HashSet<char> h = new HashSet<char>(input); Console.Write("Guessed so far:"); while (h.Count != 0) { Console.Write(" " + h.First()); h.Remove(h.First()); } Console.Write("\n Hangman: "); for (int i = 0; i < answer.Length; i++) { if (input.Contains(answer[i])) Console.Write(answer[i]); else Console.Write('_'); } Console.Write("\n\n"); }
public override void BuildNode (ITreeBuilder treeBuilder, object dataObject, NodeInfo nodeInfo) { //modules do no have names/IDs, but genrally the only reason they exist //is because they have additional, optional dependencies //so find the dependencies that are not referenced in other modules //and use one as the label var module = (ModuleDescription)dataObject; var deps = new HashSet<string> (); foreach (Dependency dep in module.Dependencies) { deps.Add (dep.Name); } foreach (ModuleDescription other in module.ParentAddinDescription.AllModules) { if (other == module) { continue; } foreach (Dependency dep in other.Dependencies) { deps.Remove (dep.Name); } } if (deps.Count > 0) { nodeInfo.Label = deps.First ().Split (new[] { ' '})[0]; } else { nodeInfo.Label = "Module"; } }
private static void Main() { var input = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); var n = input[0]; var coord0 = new Coord(input[1], input[2]); var rgcoord = new HashSet<Coord>(); for (var i = 0; i < n; i++) { input = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); rgcoord.Add(new Coord(input[0], input[1])); } var d = 0; while (rgcoord.Any()) { d++; var coord = rgcoord.First(); var vX = coord.x - coord0.x; var vY = coord.y - coord0.y; foreach (var coordT in rgcoord.ToList()) { if (vY*(coordT.x - coord0.x) == vX*(coordT.y - coord0.y)) rgcoord.Remove(coordT); } } Console.WriteLine(d); }
public FeatureInteraction(HashSet<XgbTreeNode> interaction, double gain, double cover, double pathProbability, double depth, double treeIndex, double fScore = 1) { SplitValueHistogram = new SplitValueHistogram(); List<string> features = interaction.OrderBy(x => x.Feature).Select(y => y.Feature).ToList(); Name = string.Join("|", features); Depth = interaction.Count - 1; Gain = gain; Cover = cover; FScore = fScore; FScoreWeighted = pathProbability; AverageFScoreWeighted = FScoreWeighted / FScore; AverageGain = Gain / FScore; ExpectedGain = Gain * pathProbability; TreeIndex = treeIndex; TreeDepth = depth; AverageTreeIndex = TreeIndex / FScore; AverageTreeDepth = TreeDepth / FScore; HasLeafStatistics = false; if (Depth == 0) { SplitValueHistogram.AddValue(interaction.First().SplitValue); } }
public static Bitmap FillBackGround(Point e, Bitmap bmpSource, int partition,Color fillColor) { int c; Bitmap bmp = new Bitmap(bmpSource); HashSet<Point> pts = new HashSet<Point>(); HashSet<Point> result = new HashSet<Point>(); pts.Add(e); result.Add(e); while (pts.Count > 0) { Point p = pts.First(); int x = p.X; int y = p.Y; c = bmpSource.GetPixel(x, y).R; bmp.SetPixel(x, y, fillColor); for (int i = -1; i < 2; i++) for (int j = -1; j < 2; j++) { int a = x + i; int b = y + j; if (a > -1 && a < bmp.Width && b > -1 && b < bmp.Height && bmpSource.GetPixel(a, b).R > c - partition && bmpSource.GetPixel(a, b).R < c + partition && !result.Contains(new Point(a, b))) { pts.Add(new Point(a, b)); result.Add(new Point(a, b)); } } pts.Remove(p); } return bmp; }
private void CalculateBodyAndPivots() { var parentCfg = Scope.Parent.LocalCfg; var cflow = new List<ControlFlowBlock>(); var pivots = new List<ControlFlowBlock>(); var todo = new HashSet<ControlFlowBlock>{Head}; while (todo.IsNotEmpty()) { var v = todo.First(); cflow.Add(v); todo.Remove(v); var h_pivots = Scope.Hierarchy().SelectMany(s => s.Pivots); if (h_pivots.Contains(v)) { pivots.Add(v); } else { var inEdges = parentCfg.TreeVedges(null, v); var innerEdges = parentCfg.Edges(cflow, cflow); var rootEdge = parentCfg.Vedge(Root, v); inEdges.Except(innerEdges).Except(rootEdge).AssertEmpty(); var outEdges = parentCfg.Vedges(v, null); var pending = outEdges.Select(e => e.Target).Where(v1 => !cflow.Contains(v1)); pending.ForEach(v1 => todo.Add(v1)); } } Body = cflow.Except(pivots).ToReadOnly(); Pivots = pivots.ToReadOnly(); }
public static HashSet<Point> getConnectedPicture(Point e, Bitmap bmpSource) { Color c = bmpSource.GetPixel(e.X, e.Y); Bitmap bmp = new Bitmap(bmpSource.Width, bmpSource.Height); HashSet<Point> pts = new HashSet<Point>(); HashSet<Point> result = new HashSet<Point>(); pts.Add(e); result.Add(e); while (pts.Count > 0) { Point p = pts.First(); int x = p.X; int y = p.Y; bmp.SetPixel(x, y, c); for (int i = -1; i < 2; i++) for (int j = -1; j < 2; j++) { int a = x + i; int b = y + j; if (a > -1 && a < bmp.Width && b > -1 && b < bmp.Height && bmpSource.GetPixel(a, b) == c && bmp.GetPixel(a, b) != c) { pts.Add(new Point(a, b)); result.Add(new Point(a, b)); } } pts.Remove(p); } return result; }
public int[] FindBest() { var remaining = new HashSet<Point>(_cities); var first = remaining.First(); var route = new List<Point> { first }; remaining.Remove(first); var numericRoute = new List<int>{_cities.IndexOf(first)}; var distance = 0.0d; while (remaining.Any()) { var shortest = double.MaxValue; Point next = null; foreach (var p in remaining) { var d = Distance(route.Last(), p); if (d < shortest) { shortest = d; next = p; } } route.Add(next); numericRoute.Add(_cities.IndexOf(next)); remaining.Remove(next); distance += shortest; } distance += Distance(route.First(), route.Last()); Console.WriteLine("Distance calculated in closestneighbour: " + distance); return numericRoute.ToArray(); }
/// <summary> /// When the tessellated solid is sliced at the specified plane, the contact surfaces are /// described by the return ContactData object. This is a non-destructive function typically /// used to find the shape and size of 2D surface on the prescribed plane.. /// </summary> /// <param name="plane">The plane.</param> /// <param name="ts">The ts.</param> /// <returns>ContactData.</returns> /// <exception cref="System.Exception">Contact Edges found that are not contained in loop.</exception> public static ContactData DefineContact(Flat plane, TessellatedSolid ts) { var vertexDistancesToPlane = new double[ts.NumberOfVertices]; for (int i = 0; i < ts.NumberOfVertices; i++) vertexDistancesToPlane[i] = ts.Vertices[i].Position.dotProduct(plane.Normal) - plane.DistanceToOrigin; // the edges serve as the easiest way to identify where the solid is interacting with the plane. // Instead of a foreach, the while loop lets us look ahead to known edges that are irrelevant. var edgeHashSet = new HashSet<Edge>(ts.Edges); // Contact elements are constructed and then later arranged into loops. Loops make up the returned object, ContactData. var straddleContactElts = new List<ContactElement>(); var inPlaneContactElts = new List<CoincidentEdgeContactElement>(); while (edgeHashSet.Any()) { // instead of the foreach, we have this while statement and these first 2 lines to enumerate over the edges. var edge = edgeHashSet.First(); edgeHashSet.Remove(edge); var toDistance = vertexDistancesToPlane[edge.To.IndexInList]; var fromDistance = vertexDistancesToPlane[edge.From.IndexInList]; if (StarMath.IsNegligible(toDistance) && StarMath.IsNegligible(fromDistance)) ContactElement.MakeInPlaneContactElement(plane, edge, edgeHashSet, vertexDistancesToPlane, inPlaneContactElts); else if ((toDistance > 0 && fromDistance < 0) || (toDistance < 0 && fromDistance > 0)) straddleContactElts.Add(new ThroughFaceContactElement(plane, edge, toDistance)); } foreach (var contactElement in inPlaneContactElts) { // next, we find any additional vertices that just touch the plane but don't have in-plane edges // to facilitate this we negate all vertices already captures in the inPlaneContactElts vertexDistancesToPlane[contactElement.StartVertex.IndexInList] = double.NaN; vertexDistancesToPlane[contactElement.EndVertex.IndexInList] = double.NaN; } for (int i = 0; i < ts.NumberOfVertices; i++) { if (!StarMath.IsNegligible(vertexDistancesToPlane[i])) continue; var v = ts.Vertices[i]; PolygonalFace negativeFace, positiveFace; if (ThroughVertexContactElement.FindNegativeAndPositiveFaces(plane, v, vertexDistancesToPlane, out negativeFace, out positiveFace)) straddleContactElts.Add(new ThroughVertexContactElement(v, negativeFace, positiveFace)); } straddleContactElts.AddRange(inPlaneContactElts); var loops = new List<Loop>(); var numberOfTries = 0; while (straddleContactElts.Any() && numberOfTries < straddleContactElts.Count) { // now build loops from stringing together contact elements var loop = FindLoop(plane, straddleContactElts, vertexDistancesToPlane); if (loop != null) { Debug.WriteLine(loops.Count + ": " + loop.MakeDebugContactString() + " "); loops.Add(loop); numberOfTries = 0; } else numberOfTries++; } if (straddleContactElts.Any()) Debug.WriteLine("Contact Edges found that are not contained in loop."); return new ContactData(loops); }
public void QueryTerm_bases_hashing_on_escaped_value() { var t1 = new QueryTerm("a", "x", false, false); var t2 = new QueryTerm("a", "y", true, false); var set = new HashSet<QueryTerm>(); set.Add(t1); set.Add(t2); Assert.AreEqual(1, set.Count); Assert.AreEqual("a", set.First().Escaped); }
public void ControllerNameByClassConvention() { var testedType = typeof (TestClassEndingController); var result = GetScanner().Scan(testedType).ToArray(); var expectation = typeof(TestClassEndingController).Name.Substring(0, typeof(TestClassEndingController).Name.Length - 10); var results = new HashSet<string>(result.Select(s => s.ControllerName)); Assert.That(results.Count, Is.EqualTo(1)); Assert.That(results.First(), Is.EqualTo(expectation)); }
public void ControllerNameByClassUnconventional() { var testedType = typeof (TestClassNonConventional); var result = GetScanner().Scan(testedType).ToArray(); var expectation = typeof(TestClassNonConventional).Name; var results = new HashSet<string>(result.Select(s => s.ControllerName)); Assert.That(results.Count, Is.EqualTo(1)); Assert.That(results.First(), Is.EqualTo(expectation)); }
public void ControllerNameByAttribute() { var testedType = typeof (TestClassWithControllerAttribute); var result = GetScanner().Scan(testedType).ToArray(); var expectation = TestClassWithControllerAttribute.ControllerName; var results = new HashSet<string>(result.Select(s => s.ControllerName)); Assert.That(results.Count, Is.EqualTo(1)); Assert.That(results.First(), Is.EqualTo(expectation)); }
public override bool Invoke(ulong steamId, long playerId, string messageText) { if (messageText.Equals("/deleteship", StringComparison.InvariantCultureIgnoreCase)|| messageText.Equals("/delship", StringComparison.InvariantCultureIgnoreCase)) { var entity = Support.FindLookAtEntity(MyAPIGateway.Session.ControlledObject, true, false, false, false, false, false); if (entity != null) { var shipEntity = entity as Sandbox.ModAPI.IMyCubeGrid; if (shipEntity != null) { DeleteShip(entity); return true; } } MyAPIGateway.Utilities.ShowMessage("deleteship", "No ship targeted."); return true; } var match = Regex.Match(messageText, @"/((delship)|(deleteship))\s+(?<Key>.+)", RegexOptions.IgnoreCase); if (match.Success) { var shipName = match.Groups["Key"].Value; var currentShipList = new HashSet<IMyEntity>(); MyAPIGateway.Entities.GetEntities(currentShipList, e => e is Sandbox.ModAPI.IMyCubeGrid && e.DisplayName.Equals(shipName, StringComparison.InvariantCultureIgnoreCase)); if (currentShipList.Count == 1) { DeleteShip(currentShipList.First()); return true; } else if (currentShipList.Count == 0) { int index; if (shipName.Substring(0, 1) == "#" && Int32.TryParse(shipName.Substring(1), out index) && index > 0 && index <= CommandListShips.ShipCache.Count && CommandListShips.ShipCache[index - 1] != null) { DeleteShip(CommandListShips.ShipCache[index - 1]); CommandListShips.ShipCache[index - 1] = null; return true; } } else if (currentShipList.Count > 1) { MyAPIGateway.Utilities.ShowMessage("deleteship", "{0} Ships match that name.", currentShipList.Count); return true; } MyAPIGateway.Utilities.ShowMessage("deleteship", "Ship name not found."); return true; } return false; }
private static string GetRequestedByFromChangeset(IEnumerable<IBuildInformationNode> changesets) { var users = new HashSet<String>(); foreach (var changeset in changesets) users.Add(changeset.Fields["CheckedInBy"]); var count = users.Count(); if (count > 1) return "(Multiple Users)"; return users.First(); }
public static IEnumerable<IEnumerable<Vertex>> GetConnectedComponents( this IGraph graph) { HashSet<Vertex> remainingVertices = new HashSet<Vertex>(graph.Vertices()); while (remainingVertices.Count > 0) { IEnumerable<Vertex> componentVertices = graph.BreadthFirstTreeTraversal(remainingVertices.First()); remainingVertices.ExceptWith(componentVertices); yield return componentVertices; } }
static void Main() { #if DEBUG Console.SetIn(new System.IO.StreamReader("../../input.txt")); #endif var nodes = new HashSet<int>(); var edges = new List<KeyValuePair<Tuple<int, int>, int>>(); foreach (int i in Enumerable.Range(0, int.Parse(Console.ReadLine()))) { int[] parts = Console.ReadLine().Split().Select(int.Parse).ToArray(); nodes.Add(parts[0]); nodes.Add(parts[1]); edges.Add(new KeyValuePair<Tuple<int, int>, int>( new Tuple<int, int>(parts[0], parts[1]), parts[2] )); } var trees = new HashSet<HashSet<int>>(); foreach (int node in nodes) { var tree = new HashSet<int>(); tree.Add(node); trees.Add(tree); } int result = 0; foreach (var currentEdge in edges.OrderBy(kvp => kvp.Value)) { var tree1 = trees.First(tree => tree.Contains(currentEdge.Key.Item1)); var tree2 = trees.Last(tree => tree.Contains(currentEdge.Key.Item2)); if (tree1 == tree2) continue; tree1.UnionWith(tree2); trees.Remove(tree2); result += currentEdge.Value; if (trees.Count == 1) break; } Console.WriteLine(result); }
//Validate that the we are using valid colors and set appropriate defaults if not. private void CheckForInvalidColorData() { HashSet<Color> validColors = new HashSet<Color>(); validColors.AddRange(TargetNodes.SelectMany(x => ColorModule.getValidColorsForElementNode(x, true))); if (validColors.Any() && (!validColors.Contains(_data.StaticColor) || !_data.ColorGradient.GetColorsInGradient().IsSubsetOf(validColors))) //Discrete colors specified { _data.ColorGradient = new ColorGradient(validColors.DefaultIfEmpty(Color.White).First()); _data.StaticColor = validColors.First(); } }
public void ShouldCreateCSharpAssemblyInfoFileAtPathWhenNotExistsAndEnsureAssemblyInfo() { var fileSystem = new TestFileSystem(); const string workingDir = "C:\\Testing"; ISet<string> assemblyInfoFile = new HashSet<string> { @"src\Project\Properties\VersionAssemblyInfo.cs" }; var fullPath = Path.Combine(workingDir, assemblyInfoFile.First()); var variables = VariableProvider.GetVariablesFor(SemanticVersion.Parse("1.0.0", "v"), new TestEffectiveConfiguration(), false); using (new AssemblyInfoFileUpdate(new Arguments { EnsureAssemblyInfo = true, UpdateAssemblyInfo = true, UpdateAssemblyInfoFileName = assemblyInfoFile }, workingDir, variables, fileSystem)) { fileSystem.ReadAllText(fullPath).ShouldMatchApproved(); } }
public CommandTarget ParseTarget(string target) { if (string.IsNullOrEmpty(target)) return new FullSuiteTarget(suite); else { if (suite.HasProduct(target)) { var product = suite.GetProduct(target); return new ProductTarget(product); } if (suite.HasModule(target)) { var module = suite.GetModule(target); return new ModuleTarget(module); } else { var matches = new HashSet<Project>(); // Looking for modulename.projectname matches foreach (var module in suite.Modules) { if (target.StartsWith(module.Name + '.', StringComparison.InvariantCultureIgnoreCase)) { string projectName = target.Substring(module.Name.Length + 1); if (module.HasProject(projectName)) matches.Add(module.GetProject(projectName)); else if (module.HasTestProject(projectName)) matches.Add(module.GetTestProject(projectName)); } } // If there is only one match if (matches.Count == 1) { var project = matches.First(); return new ProjectTarget(project); } else { if (matches.Count > 1) throw new ArgumentException( "The given module and project name identifies more than one projects", "target"); else throw new ArgumentException("The given project does not exist", "target"); } } } }
public PathData pathTo(Pos target, Pos currentLocation, Tile[][] board, int spikeCost = 5) { Dictionary<string, InternalTile> Navigated = new Dictionary<string, InternalTile>(); HashSet<InternalTile> Closed = new HashSet<InternalTile>(); InternalTile beginning = new InternalTile() { TilePos = currentLocation, Weight = 0 }; HashSet<InternalTile> Opened = new HashSet<InternalTile> { beginning }; Dictionary<string, int> Scores = new Dictionary<string, int> { {GetKey(beginning.TilePos.x, beginning.TilePos.y), beginning.Weight} }; Dictionary<string, float> FullScores = new Dictionary<string, float> { {GetKey(beginning.TilePos.x, beginning.TilePos.y), GetDistance(currentLocation, target)} }; while (Opened.Any()) { InternalTile lowest = Opened.First(tile => GetKey(tile.TilePos.x, tile.TilePos.y) == GetLowestCostTile(FullScores, Opened)); if (lowest.TilePos.x == target.x && lowest.TilePos.y == target.y) { return ReconstructPath(Navigated, target); } Opened.Remove(lowest); Closed.Add(lowest); foreach (Pos neighbor in GetNeighbors(lowest.TilePos, board.Length, board[0].Length)) { if (Closed.Any(tile => tile.TilePos.x == neighbor.x && tile.TilePos.y == neighbor.y)) { continue; } string neighborKey = GetKey(neighbor.x, neighbor.y); int curScore = Scores[GetKey(lowest.TilePos.x, lowest.TilePos.y)] + 1; if (!Opened.Any(tile => tile.TilePos.x == neighbor.x && tile.TilePos.y == neighbor.y)) { Opened.Add(new InternalTile { TilePos = new Pos { x = neighbor.x, y = neighbor.y } }); } else if (curScore >= (Scores.ContainsKey(neighborKey) ? Scores[neighborKey] : int.MaxValue)) { continue; } Navigated.Add(neighborKey, lowest); Scores.Add(neighborKey, curScore); FullScores.Add(neighborKey, curScore + GetDistance(neighbor, target)); } } return null; }
public static List<NavigationItem> GetNavigationItems(Func<string, string> resolveUrl = null, Func<NavigationItemAttribute, bool> filter = null) { var result = new List<NavigationItem>(); var menuItems = GetNavigationItemAttributes(filter); var remaining = new HashSet<string>(); foreach (var item in menuItems) remaining.Add(item.Key); Action<List<NavigationItem>, NavigationItemAttribute> processMenu = null; processMenu = (parent, menu) => { var path = (menu.Category.IsEmptyOrNull() ? "" : (menu.Category + "/")); path += (menu.Title.TrimToNull() ?? ""); remaining.Remove(path); var section = new NavigationItem { Title = menu.Title, Url = (!string.IsNullOrEmpty(menu.Url) && resolveUrl != null) ? resolveUrl(menu.Url) : menu.Url, IconClass = menu.IconClass.TrimToNull(), Target = menu.Target.TrimToNull() }; bool isAuthorizedSection = !menu.Url.IsEmptyOrNull() && (menu.Permission.IsEmptyOrNull() || Authorization.HasPermission(menu.Permission)); var children = menuItems[path]; foreach (var child in children) processMenu(section.Children, child); if (section.Children.Count > 0 || isAuthorizedSection) parent.Add(section); }; remaining.Remove(""); foreach (var menu in menuItems[""]) processMenu(result, menu); while (remaining.Count > 0) { var first = remaining.First(); remaining.Remove(first); var menu = new NavigationMenuAttribute(Int32.MaxValue, first); processMenu(result, menu); } return result; }
/// <summary> /// Generic path finding. Works on any map type. /// </summary> /// <returns>A list of paths to take to move from the start node to the goal node using the minimum number of paths, or null if no such list exists.</returns> public static List<Path> Find(IGameMap map, IMapNode start, IMapNode goal) { if (start == goal) return new List<Path>(); Dictionary<IMapNode, int> distance = new Dictionary<IMapNode, int>(); Dictionary<IMapNode, Path> previous = new Dictionary<IMapNode, Path>(); ICollection<IMapNode> unvisited = new HashSet<IMapNode>(); foreach (IMapNode node in map.Nodes) { distance.Add(node, Int32.MaxValue); previous.Add(node, null); unvisited.Add(node); } distance[start] = 0; while (unvisited.Count > 0) { IMapNode currentNode = unvisited.First(x => distance[x] == unvisited.Min(y => distance[y])); unvisited.Remove(currentNode); if (currentNode == goal) break; foreach (Path p in map.GetPathsFrom(currentNode)) { IMapNode neighbor = p.To; int alternateDistance = distance[currentNode] + 1; if (alternateDistance < distance[neighbor]) { distance[neighbor] = alternateDistance; previous[neighbor] = p; } } } List<Path> path = new List<Path>(); Path prevPath = previous[goal]; do { path.Insert(0, prevPath); prevPath = previous[prevPath.From]; } while (prevPath != null); return path; }
public void DistributedCacheEmulator_Get_WorksMultiThreaded() { var cache = new DistributedCacheEmulator(); cache.Set("MultiThreadedValue", 12345); var values = new HashSet<int>(); Parallel.ForEach(new int[100], x => { var result = cache.Get<int>("MultiThreadedValue"); lock (values) values.Add(result); }); Assert.Equal(12345, values.First()); }
public SuggestedMoves GetPath(Color[,] board) { //Get the farthest nodes TreeNode head = MapBuilder.BuildTree(board); ISet<TreeNode> farthestNodes = new HashSet<TreeNode>(); int highestDepth = 0; foreach (TreeNode node in head.BFS()) //DFS would be better { int depth = GetDepth(node); if (depth > highestDepth) { highestDepth = depth; farthestNodes.Clear(); farthestNodes.Add(node); } else if (depth == highestDepth) { farthestNodes.Add(node); } } Console.Write("Farthest nodes are "); farthestNodes.Select(n => n.Color).ToList().ForEach(c => Console.Write(c + ", ")); Console.WriteLine("\r\nFarthest node is " + GetDepth(farthestNodes.First()) + " away from the current"); //get the color that would step towards each color IDictionary<Color, int> tally = new Dictionary<Color, int>(); foreach (TreeNode farthestNode in farthestNodes) { TreeNode currentNode = farthestNode; while (currentNode.Parent != head) { currentNode = currentNode.Parent; } if (!tally.ContainsKey(currentNode.Color)) { tally.Add(currentNode.Color, 1); } else { tally[currentNode.Color]++; } } SuggestedMoves suggestedMoves = new SuggestedMoves(); suggestedMoves.AddFirst(new SuggestedMove(tally.OrderByDescending(kvp => kvp.Value).Select(n => n.Key))); return suggestedMoves; }
private Tile[] getMatchingNeighbors() { HashSet<Tile> border = new HashSet<Tile>(); border.Add(this); HashSet<Tile> explored = new HashSet<Tile>(); while (border.Count > 0) { Tile cur = border.First(); border.Remove(cur); explored.Add(cur); addIf(border, explored, cur.up); addIf(border, explored, cur.down); addIf(border, explored, cur.left); addIf(border, explored, cur.right); } return explored.ToArray(); }