IEnumerable <string> Launch() { logScreen?.WriteText("", false); Message($"Target: {TargetLocation.ToString()}"); if (ApproachIndex < 0) { var minkv = Approaches.MinBy((kv) => (float)(TargetLocation.CurrentPosition - kv.Value[0]).Length()); ChosenApproach = minkv.Key; ApproachIndex = minkv.Value.Count - 1; } if ((Approaches[ChosenApproach][0] - TargetLocation.CurrentPosition).Length() > AbortDistance) { Message("Target location is too far from the dock!"); yield return(""); } else { PreFlightPreparations(); Clamp.Unlock(); Vector3D detach = DockLocation - DockApproachVector * 2 * Me.CubeGrid.WorldVolume.Radius; Pilot.Tasks.Clear(); var task = new UnaimedFlightStrategy(detach, Connector); task.MaxLinearSpeed = MaxSpeed; Pilot.Tasks.Add(task); while (!Pilot.Update(Runtime.TimeSinceLastRun.TotalSeconds)) { yield return(null); } foreach (var cam in Cameras) { cam.EnableRaycast = true; } yield return("LeaveDock"); } }
public static IEnumerable <R> JoinSimilar <T, S, R>(this List <T> outer, List <S> inner, Func <T, string> outerKeySelector, Func <S, string> innerKeySelector, Func <T, S, int, R> resultSelector) where T : notnull where S : notnull { StringDistance sd = new StringDistance(); Dictionary <Tuple <T, S>, int> distances = (from o in outer from i in inner select KeyValuePair.Create(Tuple.Create(o, i), sd.LevenshteinDistance(outerKeySelector(o), innerKeySelector(i)))).ToDictionary(); while (distances.Count > 0) { var kvp = distances.MinBy(a => a.Value); var tuple = kvp.Key; distances.RemoveRange(distances.Keys.Where(a => a.Item1.Equals(tuple.Item1) || a.Item2.Equals(tuple.Item2)).ToList()); outer.Remove(tuple.Item1); inner.Remove(tuple.Item2); yield return(resultSelector(tuple.Item1, tuple.Item2, kvp.Value)); } }
// // Summary: // Increment the hit counter for a given client and check whether it exceeded // the maximum consecutive hits. // // Returns: // true if the caller did not exceed the maximum consecutive hits and may continue // the intended action, false otherwise. // private bool UnknownTargetHits_Hit(string clientName) { lock (UnknownTargetHitsLock) { if (UnknownTargetHits.ContainsKey(clientName)) { UnknownTargetHits[clientName]++; } else { UnknownTargetHits[clientName] = 1; } // Our dict can store at most `UnknownTargetMaxCapacity` items. if (UnknownTargetHits.Count > UnknownTargetMaxCapacity) // Count is O(1) { // Remove the key with fewer hits. string keyToBeRemoved = UnknownTargetHits.MinBy(kvp => kvp.Value).Key; UnknownTargetHits.Remove(keyToBeRemoved); } // Did reach maximum consecutive hits for this target? if (UnknownTargetHits[clientName] > UnknownTargetMaxConsecutiveHits) { return(false); } } return(true); }
Player Randomplayer(Actor self) { Player targetplayer = null; var playerarray = new Dictionary <Player, int>(); var allplayer = self.World.Players; if (allplayer.Any()) { foreach (var playerr in allplayer) { if (!playerr.NonCombatant && playerr.WinState != WinState.Lost) { playerarray.Add(playerr, playerr.PlayerActor.Trait <AttackedByDead>().AttackCount); } } } if (playerarray.Any()) { targetplayer = playerarray.MinBy(kvp => kvp.Value).Key; targetplayer.PlayerActor.Trait <AttackedByDead>().AttackCount += 1; } return(targetplayer); }
public Location NextEmpty() { if (_emptySpaces.Count == 0) { return(null); } var possibles = new Dictionary <Location, List <int> >(); foreach (var emptySpace in _emptySpaces) { possibles[emptySpace] = TotalSpaceValues.Except(UsedNumbersInSpace(emptySpace)).ToList(); if (possibles[emptySpace].Count == 1) { Set(emptySpace, possibles[emptySpace].First()); return(NextEmpty()); } } // // foreach (var possible in possibles) // { // if (possible.Value.Count == 1) // { // Set(possible.Key, possible.Value.First()); // // return NextEmpty(); // } // } return(possibles.MinBy(kvp => kvp.Value.Count()).Key); }
public List <Dictionary <PointF, List <PointF> > > Clusterize(IEnumerable <PointF> data, int clustersCount) { List <Dictionary <PointF, List <PointF> > > history = new List <Dictionary <PointF, List <PointF> > >(); List <PointF> centers = new List <PointF>(); while (centers.Count != clustersCount) { int index = Random.Next(0, data.Count()); PointF item = data.ElementAt(index); if (centers.Contains(item)) { continue; } centers.Add(item); } while (true) { Dictionary <PointF, List <PointF> > clusters = Distribute(data, centers); IEnumerable <PointF> emptyCenters = clusters.Where(cluster => cluster.Value.Count == 0).Select(kvp => kvp.Key); foreach (PointF emptyCenter in emptyCenters) { Dictionary <PointF, PointF> nearestByClusters = clusters.ToDictionary( cluster => cluster.Key, cluster => cluster.Value.MinBy(p => GetDistance(p, emptyCenter)) ); KeyValuePair <PointF, PointF> nearest = nearestByClusters.MinBy( kvp => GetDistance(kvp.Value, emptyCenter) ); clusters[emptyCenter].Add(nearest.Value); clusters[nearest.Key].Remove(nearest.Value); } Dictionary <PointF, List <PointF> > previousClusters = history.LastOrDefault(); bool finish = previousClusters != null && clusters.Values.All( points => previousClusters.Values.FirstOrDefault( prevPoints => prevPoints.Except(points).Count() == 0 ) != null ); history.Add(clusters); if (finish) { break; } centers = clusters.Values.Select(cluster => GetCenter(cluster)).ToList(); } return(history); }
public async Task <ActionResult> DisplayLowestDurationLocation() { Dictionary <DarkSkyLocation, int> locationsByDuration = new Dictionary <DarkSkyLocation, int>(); locationsByDuration = await CalculateAllDurations(); var locationKey = locationsByDuration.MinBy(l => l.Value).Key; return(View("SeeNearest", locationKey)); }
static void Main(string[] args) { var chars = Enumerable.Range('\x1', 127).Select(x => Convert.ToChar(x)).Where(x => !char.IsControl(x)).ToList(); Dictionary <char, decimal> brightness = new Dictionary <char, decimal>(); Bitmap image = new Bitmap(100, 200); Graphics graphic = Graphics.FromImage(image); Font font = new Font(new FontFamily("DejaVu Sans Mono"), 12); SolidBrush brush = new SolidBrush(Color.Black); PointF point = new PointF(1, 1); foreach (char c in chars) { graphic.Clear(Color.White); graphic.DrawString(c.ToString(), font, brush, point); SizeF ss = graphic.MeasureString(c.ToString(), font); int width = (int)ss.Width; int height = (int)ss.Height; decimal charBrightness = 0; for (int x = (int)point.X; x < width + (int)point.X; x++) { for (int y = (int)point.Y; y < height + (int)point.Y; y++) { charBrightness += (decimal)image.GetPixel(x, y).GetBrightness(); } } charBrightness = charBrightness / width / height; brightness.Add(c, charBrightness); } var maxBright = brightness.Values.AsEnumerable().Max(); Dictionary <char, decimal> relativeBrightness = new Dictionary <char, decimal>(); foreach (char c in brightness.Keys) { relativeBrightness.Add(c, brightness[c] / maxBright); } Dictionary <decimal, char> bestChars = new Dictionary <decimal, char>(); for (decimal i = 0; i <= 1; i += 0.05m) { var u = relativeBrightness.MinBy(x => Math.Abs(i - x.Value)).Item1; bestChars.Add(i, u.Key); relativeBrightness.Remove(u.Key); } using (StreamWriter writer = new StreamWriter("brightness.txt", false, Encoding.Unicode)) { foreach (decimal bright in bestChars.Keys) { writer.WriteLine($"{bright}|{bestChars[bright]}"); } writer.Close(); } }
private static void RunQuestao1() { foreach (var areaStats in AreaStatsDict.MaxBy(p => p.Value.MaxSalario)) { foreach (var funcionario in areaStats.Value.Max) { _stringBuilderResult.AppendLine($"global_max|{GetUTF8String(funcionario.Nome)} {GetUTF8String(funcionario.Sobrenome)}|{areaStats.Value.MaxSalario:0.00}"); } } foreach (var areaStats in AreaStatsDict.MinBy(p => p.Value.MinSalario)) { foreach (var funcionario in areaStats.Value.Min) { _stringBuilderResult.AppendLine($"global_min|{GetUTF8String(funcionario.Nome)} {GetUTF8String(funcionario.Sobrenome)}|{areaStats.Value.MinSalario:0.00}"); } } _stringBuilderResult.AppendLine($"global_avg|{(_totalSalarios / AreaStatsDict.Sum(a => a.Value.TotalFuncionarios)):0.00}"); }
public string SolvePart1() { Dictionary <int, List <int> > layers = CalculateLayers(Input); int indexOfLeastZeroes = layers.MinBy(l => l.Value.Count(d => d == 0)).Key; List <int>?layerWithLeastZeroes = layers[indexOfLeastZeroes]; int onesCount = layerWithLeastZeroes.Count(d => d == 1); int twosCount = layerWithLeastZeroes.Count(d => d == 2); return($"Part 1: {onesCount * twosCount}"); }
private static void PrintQuestao1() { foreach (var areaStats in AreaStatsDict.MaxBy(p => p.Value.MaxSalario)) { foreach (var funcionario in areaStats.Value.Max) { Console.WriteLine($"global_max|{GetUTF8String(funcionario.Nome)} {GetUTF8String(funcionario.Sobrenome)}|{areaStats.Value.MaxSalario:0.00}"); } } foreach (var areaStats in AreaStatsDict.MinBy(p => p.Value.MinSalario)) { foreach (var funcionario in areaStats.Value.Min) { Console.WriteLine($"global_min|{GetUTF8String(funcionario.Nome)} {GetUTF8String(funcionario.Sobrenome)}|{areaStats.Value.MinSalario:0.00}"); } } Console.WriteLine($"global_avg|{(_totalSalarios / AreaStatsDict.Sum(a => a.Value.TotalFuncionarios)):0.00}"); }
public Dictionary <TypeDeplacement, Position> Deplacer(Position currentPosition, Position posPlusProcheEnnemie, IEnumerable <Position> listPosition, Grille grille) { Dictionary <TypeDeplacement, Position> dictDeplacement = new Dictionary <TypeDeplacement, Position>(); Dictionary <TypeDeplacement, double> dictDist = new Dictionary <TypeDeplacement, double>(); Position pos = posPlusProcheEnnemie; Position positionAfterDep = new Position(null, null); #region Up if (CheckMoveValidity(TypeDeplacement.Up, pos, grille) && CheckIfCaseIsEmpty(TypeDeplacement.Up, pos, listPosition)) { positionAfterDep.LeftCursorPosition = pos.LeftCursorPosition; positionAfterDep.TopCursorPosition = pos.TopCursorPosition - 3; dictDist.Add(TypeDeplacement.Up, GetDistanceBetweenPos(currentPosition, positionAfterDep)); } #endregion #region Down if (CheckMoveValidity(TypeDeplacement.Down, pos, grille) && CheckIfCaseIsEmpty(TypeDeplacement.Down, pos, listPosition)) { positionAfterDep.LeftCursorPosition = pos.LeftCursorPosition; positionAfterDep.TopCursorPosition = pos.TopCursorPosition + 3; dictDist.Add(TypeDeplacement.Down, GetDistanceBetweenPos(currentPosition, positionAfterDep)); } #endregion #region Left if (CheckMoveValidity(TypeDeplacement.Left, pos, grille) && CheckIfCaseIsEmpty(TypeDeplacement.Left, pos, listPosition)) { positionAfterDep.LeftCursorPosition = pos.LeftCursorPosition - 5; positionAfterDep.TopCursorPosition = pos.TopCursorPosition; dictDist.Add(TypeDeplacement.Left, GetDistanceBetweenPos(currentPosition, positionAfterDep)); } #endregion #region Right if (CheckMoveValidity(TypeDeplacement.Right, pos, grille) && CheckIfCaseIsEmpty(TypeDeplacement.Right, pos, listPosition)) { positionAfterDep.LeftCursorPosition = pos.LeftCursorPosition + 5; positionAfterDep.TopCursorPosition = pos.TopCursorPosition; dictDist.Add(TypeDeplacement.Right, GetDistanceBetweenPos(currentPosition, positionAfterDep)); } #endregion var typeDepConvenable = dictDist.MinBy(x => x.Value).First().Key; dictDeplacement.Add(typeDepConvenable, pos); return(dictDeplacement); }
public string SolvePart2() { IEnumerable<char> distinctUnitTypes = Input.Select(char.ToUpper).ToList().Distinct(); var polymerOptions = new Dictionary<char, int>(); // Key: Removed Unit Type, Value: Collapsed Length foreach (char unitType in distinctUnitTypes) { List<char> improvedPolymer = Input.ToList(); // "Copy" the Input improvedPolymer.RemoveAll(i => char.ToUpper(i) == unitType); IList<char> collapsedPolymer = ReactPolymer(improvedPolymer); polymerOptions.Add(unitType, collapsedPolymer.Count); } KeyValuePair<char, int> optimalPolymer = polymerOptions.MinBy(o => o.Value).FirstOrDefault(); return $"Part 2: {optimalPolymer.Value}"; }
internal Action GetBestActionFor(Precondition precondition) { var possibleActions = new Dictionary <Action, float>(); var state = EntityStateProvider.EntityState.Clone(); precondition.SetVariables(state); Debug.Log("Finding best action for " + precondition); foreach (var knownAction in KnownActions) { if (knownAction.SatisfiesPrecondition(precondition) && knownAction.IsPossible(this, state)) { var cost = CalculateCost(knownAction); possibleActions[knownAction] = cost; Debug.Log("Cost for action " + knownAction + " = " + cost); } } return(possibleActions.MinBy(pair => pair.Value).Key); }
public P039 () { var res = new Dictionary<int, int> (); for (int p = 3; p <= 1000; p++) { int n = 0; for (int a = 1; a <= p - 2; a++) { for (int b = a; a + b <= p - 1; b++) { var c = p - a - b; if (a * a + b * b == c * c) { Console.WriteLine (p + "\t" + a + "\t" + b + "\t" + c); n++; } } } res.Add (p, n); } Console.WriteLine (res.MinBy (x => -x.Value)); }
public string SolvePart1() { var currentLocation = new Location(0, 0); while (currentLocation.X <= XBoundary && currentLocation.Y <= YBoundary) { Dictionary <Location, int> distances = AllLocations.ToDictionary(location => location, location => CalculateManhattanDistance(currentLocation, location)); IExtremaEnumerable <KeyValuePair <Location, int> >?sortedDistances = distances.MinBy(d => d.Value); KeyValuePair <Location, int> shortestDistance = sortedDistances.First(); if (sortedDistances.Count() == 1 || sortedDistances.Count(s => s.Value == shortestDistance.Value) == 1) { // Only add if the current location is closest to a single point. var newLocation = new Location(currentLocation.X, currentLocation.Y) { IsInfinite = currentLocation.X == 0 || currentLocation.Y == 0 || currentLocation.X == XBoundary || currentLocation.Y == YBoundary }; AllLocations.SingleOrDefault(l => l == shortestDistance.Key)?.ClosestLocations.Add(newLocation); } // Move to the next location if (currentLocation.Y == YBoundary) { currentLocation.X++; currentLocation.Y = 0; } else { currentLocation.Y++; } } List <Location> nonInfiniteLocations = AllLocations.Where(l => l.ClosestLocations.All(c => !c.IsInfinite)).ToList(); Location? largestNonInfinite = nonInfiniteLocations.MaxBy(l => l.ClosestLocations.Count).First(); return($"Part 1: {largestNonInfinite.ClosestLocations.Count}"); }
public List <string> PathDetermination() { Dictionary <string, int[]> destinations = new Dictionary <string, int[]> { { "Unilag", point1 }, { "Yabatech", point2 }, { "Fce", point3 }, { "Lasu", point4 }, { "Laspotech", point5 } }; var len = destinations.Count; var startposition = TravelerPosition(); var path = new List <string>(); for (int i = 0; i < len; i++) { Dictionary <string, int> dist = new Dictionary <string, int>(); foreach (var dic in destinations) { dist[dic.Key] = Distance(startposition, dic.Value); } var shortdist = dist.MinBy(distance => distance.Value).Value; for (int j = 0; j < dist.Count; j++) { var distance = dist.ElementAt(j); if (distance.Value == shortdist) { path.Add(distance.Key); destinations.Remove((distance.Key)); } } } return(path); }
public override string GetLabel() { GetAffectedThings(); garbageCollectDeadPawns(); if (bleeders.Count == 0) { return(""); } // stave off empty collection error as alert is fading var minBleeder = bleeders.MinBy(kvp => kvp.Value); if (minBleeder.Value < 12500) { this.defaultPriority = AlertPriority.Critical; } else { this.defaultPriority = AlertPriority.High; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine(affectedThings.Count() + " " + this.defaultLabel); stringBuilder.AppendLine(pawnBleedString(minBleeder.Key.Name.ToStringShort, minBleeder.Value)); return(stringBuilder.ToString().TrimEnd('\n'));; }
public virtual void AskForReplacements( HashSet <string> oldKeys, HashSet <string> newKeys, string replacementsKey) { List <string> oldOnly = oldKeys.Where(k => !newKeys.Contains(k)).ToList(); List <string> newOnly = newKeys.Where(k => !oldKeys.Contains(k)).ToList(); if (oldOnly.Count == 0 || newOnly.Count == 0) { return; } Dictionary <string, string> replacements = this.TryGetC(replacementsKey) ?? new Dictionary <string, string>(); if (replacements.Any()) { var toRemove = replacements.Where(a => oldOnly.Contains(a.Key) && newOnly.Contains(a.Value)).ToList(); foreach (var kvp in toRemove) { oldOnly.Remove(kvp.Key); newOnly.Remove(kvp.Value); } } if (oldOnly.Count == 0 || newOnly.Count == 0) { return; } StringDistance sd = new StringDistance(); Dictionary <string, Dictionary <string, float> > distances = oldOnly.ToDictionary(o => o, o => newOnly.ToDictionary(n => n, n => { return(Distance(sd, o, n)); })); new Dictionary <string, string>(); while (oldOnly.Count > 0 && newOnly.Count > 0) { var oldDist = distances.MinBy(kvp => kvp.Value.Values.Min()); var alternatives = oldDist.Value.OrderBy(a => a.Value).Select(a => a.Key).ToList(); Selection selection = SelectInteractive(oldDist.Key, alternatives, replacementsKey, Interactive); oldOnly.Remove(selection.OldValue); distances.Remove(selection.OldValue); if (selection.NewValue != null) { replacements.Add(selection.OldValue, selection.NewValue); newOnly.Remove(selection.NewValue); foreach (var dic in distances.Values) { dic.Remove(selection.NewValue); } } } if (replacements.Count != 0 && !this.ContainsKey(replacementsKey)) { this.GetOrCreate(replacementsKey).SetRange(replacements); } }
public override LayoutDTO GetNextPiece() { var nextPiece = pieceQueue.Peek(); var possiblePlays = Board.Instance.PossiblePlays(nextPiece.Layout); LayoutDTO layoutValues; if (possiblePlays > 0) { //Creates a new piecePreview to be enqueued var newPiecePreview = GameControl.Instantiate(GameController.previewPiecePrefab, new Vector3(PIECE_PREVIEW_INITIAL_X, -0.6f, 0), Quaternion.identity) as PreviewPiece; newPiecePreview.gameObject.name = GameController.previewPiecePrefab.name; //Selects what layout that piece will have var minUsage = layoutUsage.MinBy(x => x.Value); var newIndex = layoutUsage.Where(x => x.Value <= minUsage.Value + 1).RandomElement().Key; layoutUsage[newIndex]++; //Enqueues the new piecePreview newPiecePreview.Init(GameController.PieceLayouts[newIndex].Copy(), newIndex); pieceQueue.Enqueue(newPiecePreview); var position = 0; foreach (var piecePreview in pieceQueue) { iTween.MoveTo(piecePreview.gameObject, iTween.Hash( "name", "tweenY", "y", PIECE_PREVIEW_INITIAL_Y + (TOTAL_PIECE_PREVIEWS - position++) * 1.6f, "time", 1f)); } //Dequeues top piece var headPiece = pieceQueue.Dequeue(); layoutValues = new LayoutDTO { Layout = headPiece.Layout, Variant = headPiece.Variant }; iTween.ValueTo(headPiece.gameObject, iTween.Hash( "name", "tweenAlpha", "from", 1f, "to", 0f, "time", 0.25f, "easetype", "easeOutCubic", "onupdate", "TweenAlpha", "oncomplete", "Destroy")); //Destroy(headPiece.gameObject); } else { var layout = new Grid <int>(); layout[0, 0] = 4; layoutValues = new LayoutDTO { Layout = layout, Variant = Block.TOTAL_VARIANTS + 1 }; //This is a heart piece if (GameController.lifeCounter.Count >= 1) { GameController.lifeCounter.Count++; } } if (UserHasPlayed) //If the player has already started playing { StopCoroutine("DecreaseMultiplier"); StartCoroutine("DecreaseMultiplier"); hintTimer = TIME_TILL_HINT; } return(layoutValues); }
public static IEnumerable <GraphNode <TK, TV> > AStar <TK, TV>( this IReadableGraph <TK, TV> graph, TK from, TK to, HeuristicFunction <TK, TV> heuristicFunction ) where TK : IEquatable <TK> { var fromNode = graph[from]; var toNode = graph[to]; var closedSet = new HashSet <GraphNode <TK, TV> >(); var openSet = new HashSet <GraphNode <TK, TV> > { fromNode }; var cameFrom = new Dictionary <GraphNode <TK, TV>, GraphNode <TK, TV> >(); var gScore = new Dictionary <GraphNode <TK, TV>, double>(); var fScore = new Dictionary <GraphNode <TK, TV>, double>(); foreach (var node in graph.Nodes) { cameFrom[node] = null; gScore[node] = PositiveInfinity; fScore[node] = PositiveInfinity; } gScore[fromNode] = 0; fScore[fromNode] = heuristicFunction(graph, fromNode, toNode); while (openSet.Count > 0) { var current = openSet.First(x => x.Equals(fScore.MinBy(kv => kv.Value).Key)); if (current.Equals(toNode)) { return(ReconstructPath(cameFrom, current)); } openSet.Remove(current); closedSet.Add(current); foreach (var connection in graph.ConnectionsOf[current]) { if (closedSet.Contains(connection.Key)) { continue; } var tentativeGScore = gScore[current] + connection.Value; if (!openSet.Contains(connection.Key)) { openSet.Add(connection.Key); } else if (tentativeGScore >= gScore[connection.Key]) { continue; } cameFrom[connection.Key] = current; gScore[connection.Key] = tentativeGScore; fScore[connection.Key] = gScore[connection.Key] + heuristicFunction(graph, connection.Key, toNode); } } return(new GraphNode <TK, TV> [0]); }
private static List <State> AStar() { var opened = new Dictionary <string, State>(); var closed = new Dictionary <string, State>(); State first = new State { Name = CrtPzlName(eightPzl), G_Score = 0, F_Score = Heuristic(eightPzl), CPuzzle = eightPzl, Previous = null, }; opened.Add(first.Name, first); bool finished = false; bool showDebug = true; while (!finished) { Console.WriteLine("\n" + new string('-', 40)); if (opened.Count == 0) { finished = true; } else { State current = opened.MinBy(n => n.Value.F_Score).Value; if (current.Previous != null) { Console.WriteLine("\nDisplay previous state"); Console.WriteLine(""); DisplayDebug(current.Previous); } Console.WriteLine("\nDisplay current state"); Console.WriteLine(""); DisplayDebug(current); if (PzlMatch(current.CPuzzle, target)) { finished = true; closed.Add(current.Name, current); } else { int x = 0; int y = 0; GetEmptyPoint(current.CPuzzle, out x, out y); var neighbours = GetNeighbours(current, x, y, current.Previous); Console.WriteLine("\nDisplaying neighbours"); opened.Remove(current.Name); foreach (var neighbour in neighbours) { if (neighbour.Name == current.Previous?.Name) { continue; } Console.WriteLine(""); DisplayDebug(neighbour); var newGScore = current.G_Score + 1; if (opened.ContainsKey(neighbour.Name) && newGScore < opened[neighbour.Name].G_Score) { UpdateExistingNeigbour(opened, neighbour, newGScore, current); } else if (closed.ContainsKey(neighbour.Name) && newGScore < closed[neighbour.Name].G_Score) { UpdateExistingNeigbour(closed, neighbour, newGScore, current); } else if (!opened.ContainsKey(neighbour.Name) && !closed.ContainsKey(neighbour.Name)) { UpdateNeighbour(neighbour, newGScore, current); opened.Add(neighbour.Name, neighbour); } if (NearlyDone(neighbour.CPuzzle) && showDebug) { Console.WriteLine("\nNearl done."); DisplayDebug(neighbour); showDebug = false; } } } } } var path = new Stack <State>(); Console.WriteLine($"\nVisit Count {closed.Count}"); GetPath(path, closed.Values.LastOrDefault()); return(path.ToList()); }
private static List <Node> GetMoves(int cx, int cy, int tx, int ty) { var visited = new Dictionary <string, Node>(); var unVisited = new Dictionary <string, Node>(); for (int r = 0; r < aSortedGrid.GetLength(0); r++) { for (int c = 0; c < aSortedGrid.GetLength(1); c++) { var n = new Node { Name = aSortedGrid[r, c], F_Score = int.MaxValue, G_Score = int.MaxValue, Row = r, Column = c, Previous = null, }; unVisited.Add(aSortedGrid[r, c], n); } } Node start = unVisited[aSortedGrid[cx, cy]]; Node taregt = unVisited[aSortedGrid[tx, ty]]; start.G_Score = 0; start.F_Score = Heuristic(cx, cy, tx, ty); bool finished = false; while (!finished) { if (unVisited.Count == 0) { finished = true; } else { Node current = unVisited.MinBy(n => n.Value.F_Score).Value; if (current.Name == taregt.Name) { finished = true; visited.Add(current.Name, current); } else { List <string> neighbours = GetNeighbours(current.Row, current.Column); foreach (var neighbour in neighbours) { if (!visited.ContainsKey(neighbour)) { var newGScore = current.G_Score + 1; // + distance from neighbour if (newGScore < unVisited[neighbour].G_Score) { unVisited[neighbour].G_Score = newGScore; unVisited[neighbour].F_Score = newGScore + Heuristic(unVisited[neighbour].Row, unVisited[neighbour].Column, tx, ty); unVisited[neighbour].Previous = current; } } } visited.Add(current.Name, current); unVisited.Remove(current.Name); } } } var path = new Stack <Node>(); GetPath(path, visited.Values.LastOrDefault()); return(path.ToList()); }
Path Node2NodeSP(Node source, Node destination) { Dictionary <Node, float> distances = new Dictionary <Node, float>(); Dictionary <Node, Pair <Road, Node> > parentness = new Dictionary <Node, Pair <Road, Node> >(); foreach (Node n in allnodes.Values) { distances[n] = Mathf.Infinity; } distances[source] = 0f; while (distances.Count > 0) { Node closestNode = distances.MinBy((KeyValuePair <Node, float> arg1) => arg1.Value).Key; foreach (Road r1 in closestNode.connection) { Node neighbor = null; if (Algebra.isclose(r1.curve.at(0f), closestNode.position) && r1.validLaneCount(true) > 0) { findNodeAt(r1.curve.at(1f), out neighbor); } else { if (Algebra.isclose(r1.curve.at(1f), closestNode.position) && r1.validLaneCount(false) > 0) { findNodeAt(r1.curve.at(0f), out neighbor); } } float w1 = r1.SPWeight; if (neighbor != null && distances.ContainsKey(neighbor) && distances[neighbor] > distances[closestNode] + w1) { distances[neighbor] = distances[closestNode] + w1; parentness[neighbor] = new Pair <Road, Node>(r1, closestNode); } } distances.Remove(closestNode); } if (parentness.ContainsKey(destination) || source.Equals(destination)) { List <Road> sp = new List <Road>(); List <Node> AllPassingNodes = new List <Node>(); Node currentNode = destination; AllPassingNodes.Add(currentNode); while (parentness.ContainsKey(currentNode)) { sp.Add(parentness[currentNode].First); currentNode = parentness[currentNode].Second; AllPassingNodes.Add(currentNode); } sp.Reverse(); AllPassingNodes.Reverse(); return(new Path(AllPassingNodes, sp)); } else { return(null); } }
public Location NextEmpty() { if (_emptySpaces.Count == 0) { return null; } var possibles = new Dictionary<Location, List<int>>(); foreach (var emptySpace in _emptySpaces) { possibles[emptySpace] = TotalSpaceValues.Except(UsedNumbersInSpace(emptySpace)).ToList(); if (possibles[emptySpace].Count == 1) { Set(emptySpace, possibles[emptySpace].First()); return NextEmpty(); } } // // foreach (var possible in possibles) // { // if (possible.Value.Count == 1) // { // Set(possible.Key, possible.Value.First()); // // return NextEmpty(); // } // } return possibles.MinBy(kvp => kvp.Value.Count()).Key; }