当前位置: 首页>>代码示例>>C#>>正文


C# HashSet.Min方法代码示例

本文整理汇总了C#中HashSet.Min方法的典型用法代码示例。如果您正苦于以下问题:C# HashSet.Min方法的具体用法?C# HashSet.Min怎么用?C# HashSet.Min使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在HashSet的用法示例。


在下文中一共展示了HashSet.Min方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: Main

    static void Main(string[] args)
    {
        int N = int.Parse(Console.ReadLine());
        HashSet<House> Houses = new HashSet<House>();
        long amountOfCable = 0;
        for (int i = 0; i < N; i++)
        {
            string[] inputs = Console.ReadLine().Split(' ');
            Houses.Add(new House { X = int.Parse(inputs[0]), Y = int.Parse(inputs[1]) });
        }

        //Core: Calculate Average House Y index
        double Avg = Houses.Sum(x => x.Y) / N;

        //Core:find the house closest to the Avg Y and use its Y coordinate
        int closest = Houses.OrderBy(x => Math.Abs(x.Y - Avg)).First().Y;

        //lay the mainline
        amountOfCable += (Houses.Max(x => x.X) - Houses.Min(x => x.X));

        //per other House calculate distance from location to mainline
        foreach (var i in Houses)
        {
            amountOfCable += i.Y > closest ? i.Y - closest : closest - i.Y;
        }

        // Write an action using Console.WriteLine()
        // To debug: Console.Error.WriteLine("Debug messages...");

        Console.WriteLine(amountOfCable);
    }
开发者ID:LievenVandeperre,项目名称:codinGame,代码行数:31,代码来源:10.+Network+Cabling.cs

示例2: GetNextAvailableLong

        public long GetNextAvailableLong(List<long> values, bool returnZero)
        {
            if (values == null || !values.Any())
            {
                if (returnZero)
                {
                    return 0;
                }
                else
                {
                    return 1;
                }
            }

            HashSet<long> hashSetValues = new HashSet<long>(values);

            long x = hashSetValues.Min();

            while (hashSetValues.Any(m => m == x))
            {
                x++;
                if (x == 0 && !returnZero)
                {
                    x++;
                }
            }

            return x;
        }
开发者ID:leandrobt2,项目名称:GetNextAvailableInt64,代码行数:29,代码来源:NormalSearch.cs

示例3: Main

        static void Main()
        {
            var collection = new HashSet<double> { 5.2, 8, -3.14, 0, 55 };

            Console.WriteLine(collection.Sum());
            Console.WriteLine(collection.Product());
            Console.WriteLine(collection.Min());
            Console.WriteLine(collection.Max());
            Console.WriteLine(collection.Average());
        }
开发者ID:danielkaradaliev,项目名称:TelerikAcademyAssignments,代码行数:10,代码来源:IEnumerableExtensionsMain.cs

示例4: FullRangeHit

        public void FullRangeHit(Int32 maximum)
        {
            var rolls = new HashSet<Int32>();
            while (LoopShouldStillRun() && rolls.Count < maximum)
                rolls.Add(Dice.Roll().d(maximum));

            Assert.That(rolls.Min(), Is.EqualTo(1));
            Assert.That(rolls.Max(), Is.EqualTo(maximum));
            Assert.That(rolls.Count, Is.EqualTo(maximum));
            Assert.Pass("Iterations: {0}", iterations);
        }
开发者ID:aloisdg,项目名称:RollGen,代码行数:11,代码来源:dTests.cs

示例5: HotnessDetector

        public HotnessDetector(HashSet<double> allLatitudes, HashSet<double> allLongitudes)
        {
            // Get the entire list of waypoints within a single hunt
            // (or at least every latitude and longitude)
            // and determine the bounds of the playfield.

            // The playfield width is determined from the eastmost latitude
            // of the waypoints and the westmost latitude of the waypoints.
            // The playfield height is determined from the northernmost longitude
            // of the waypoints and the southernmost longitude of the waypoints.

            playfield = new GeoArea(allLongitudes.Min(), allLongitudes.Max(), allLatitudes.Max(), allLatitudes.Min());
        }
开发者ID:pgodwin,项目名称:AlleyCat,代码行数:13,代码来源:HotnessDetector.cs

示例6: Find

        /// <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;
        }
开发者ID:HexagrammumMysticum,项目名称:TextAdventure,代码行数:53,代码来源:Path.cs

示例7: FindSmallestMemberOfChain

        public void FindSmallestMemberOfChain()
        {
            var chainLength = GetChainLength(402170);
            chainLength.Should().Be(65);
            var chain = new HashSet<long>();
            long startingNumber = 402170;

            long currentNumber = startingNumber;
            while (!chain.Contains(currentNumber))
            {
                chain.Add(currentNumber);
                var factors = FactorHelper.GetProperFactorsOf(currentNumber);
                var sum = factors.Sum();
                currentNumber = sum;
            }

            var smallest = chain.Min();
            Console.WriteLine("Smallest member of longest chain: {0}", smallest);
        }
开发者ID:kajones,项目名称:Puzzles,代码行数:19,代码来源:Problem_0095_AmicableChains.cs

示例8: Collapse


//.........这里部分代码省略.........

                            var nodeInputs = outputs
                                .Where(output => output.Item3.Item2 == outerNode)
                                .Select(
                                    output =>
                                    new
                                    {
                                        InnerNodeInputSender = output.Item1,
                                        OuterNodeInPortData = output.Item3.Item1
                                    }).ToList();

                            nodeInputs.ForEach(_ => node.AddInput());

                            node.RegisterAllPorts();

                            return new
                            {
                                OuterNode = outerNode,
                                InnerNode = node,
                                Outputs = inputs.Where(input => input.Item3.Item2 == outerNode)
                                                .Select(input => input.Item3.Item1),
                                Inputs = nodeInputs,
                                OuterNodePortDataList = inPortsConnected
                            };
                        }).ToList();

            #endregion

            #region UI Positioning Calculations

            double avgX = selectedNodeSet.Average(node => node.X);
            double avgY = selectedNodeSet.Average(node => node.Y);

            double leftMost = selectedNodeSet.Min(node => node.X);
            double topMost = selectedNodeSet.Min(node => node.Y);
            double rightMost = selectedNodeSet.Max(node => node.X + node.Width);

            #endregion

            #region Move selection to new workspace

            var connectors = new HashSet<ConnectorModel>(currentWorkspace.Connectors.Where(
                                                                conn => selectedNodeSet.Contains(conn.Start.Owner)
                                                                    && selectedNodeSet.Contains(conn.End.Owner)));

            //Step 2: move all nodes to new workspace
            //  remove from old
            foreach (var ele in selectedNodeSet)
            {
                ele.SaveResult = false;
                currentWorkspace.Nodes.Remove(ele);
                ele.WorkSpace = newNodeWorkspace;
            }
            foreach (var ele in connectors)
            {
                currentWorkspace.Connectors.Remove(ele);
            }

            //  add to new
            newNodeWorkspace.Nodes.AddRange(selectedNodeSet);
            newNodeWorkspace.Connectors.AddRange(connectors);

            double leftShift = leftMost - 250;
            foreach (NodeModel node in newNodeWorkspace.Nodes)
            {
                node.X = node.X - leftShift;
开发者ID:kscalvin,项目名称:Dynamo,代码行数:67,代码来源:NodeCollapser.cs

示例9: ColorGradientWidget

		public ColorGradientWidget(GCodeFile gcodeFileTest)
			: base(FlowDirection.TopToBottom)
		{
			BackgroundColor = new RGBA_Bytes(0, 0, 0, 120);

			HashSet<float> speeds = new HashSet<float>();
			PrinterMachineInstruction previousInstruction = gcodeFileTest.Instruction(0);
			for (int i = 1; i < gcodeFileTest.LineCount; i++)
			{
				PrinterMachineInstruction instruction = gcodeFileTest.Instruction(i);
				if (instruction.EPosition > previousInstruction.EPosition && (instruction.Line.IndexOf('X') != -1 || instruction.Line.IndexOf('Y') != -1))
				{
					speeds.Add((float)instruction.FeedRate);
				}
				previousInstruction = instruction;
			}

			ExtrusionColors extrusionColors = new ExtrusionColors();

			speeds.Select(speed => extrusionColors.GetColorForSpeed(speed)).ToArray();

			if(speeds.Count <= 0)
			{
				// There are no paths so don't generate the rest of the widget.
				return;
			}

			float min = speeds.Min();
			float max = speeds.Max();
			int maxItems = Math.Min(7, speeds.Count());

			int count = maxItems - 1;
			float increment = (max - min) / count;
			int index = 0;

			int[] rangeValues;
			if (speeds.Count < 8)
			{
				rangeValues = speeds.Select(s => (int)s).OrderBy(i => i).ToArray();
			}
			else
			{
				rangeValues = Enumerable.Range(0, maxItems).Select(x => (int)(min + increment * index++)).ToArray();
			}

			RGBA_Bytes[] speedColors = rangeValues.OrderBy(s => s).Select(speed => extrusionColors.GetColorForSpeed(speed)).ToArray();

			for (int i = 0; i < speedColors.Length; i++)
			{
				RGBA_Bytes color = speedColors[i];
				int speed = rangeValues[i];

				GuiWidget colorWidget = new GuiWidget();
				colorWidget.Width = 20;
				colorWidget.Height = 20;
				colorWidget.BackgroundColor = color;
				colorWidget.Margin = new BorderDouble(2);
				double feedRateToMMPerSecond = speed / 60;

				ColorToSpeedWidget colorToSpeedWidget = new ColorToSpeedWidget(colorWidget, feedRateToMMPerSecond);
				this.AddChild(colorToSpeedWidget);
			}

			Margin = new BorderDouble(5, 5, 200, 50);
			HAnchor |= Agg.UI.HAnchor.ParentLeft;
			VAnchor = Agg.UI.VAnchor.ParentTop;
		}
开发者ID:tellingmachine,项目名称:MatterControl,代码行数:67,代码来源:ColorGradientWidget.cs

示例10: GetRaveDetailsFromEventIDs

        public static IList<RaveDetails> GetRaveDetailsFromEventIDs(IEnumerable<Int64> eventIds)
        {
            _fb.AccessToken = _GenericAccessToken;

            string fields = "eid, name, pic_square, start_time, end_time, is_date_only, creator, update_time, location, venue";
            string eidList = string.Join(",", eventIds.ToArray());
            dynamic fqlResult = _fb.Get("fql", new { q = String.Format("SELECT {0} FROM event WHERE eid IN ({1})", fields, eidList) });
            JsonArray fqlEventResults = fqlResult.data;

            IList<RaveDetails> eventResults = new List<RaveDetails>();
            HashSet<Venue> venueResults = new HashSet<Venue>();
            HashSet<Rave> raveResults = new HashSet<Rave>();
            foreach (dynamic fqlEvent in fqlEventResults)
            {
                Int64? creatorId = fqlEvent.creator ?? 0;
                Int64? eventId = fqlEvent.eid;
                Int64? venueId = 0;
                if (fqlEvent.venue.Count > 0)
                {
                     dynamic jsonVenue = (JsonObject)fqlEvent.venue;
                     venueId = jsonVenue.id ?? 0;
                }

                Rave aRave = null;
                Venue aVenue = null;
                Owner aOwner = null;
                if (eventId != null)
                {
                    // Get the owner; no chance for duplications
                    aOwner = GetRaveOwnerFromUserID(creatorId);

                    // Before querying for the Venue, make sure we haven't already queried it
                    if (venueResults.Any(v => v.VenueID == venueId))
                    {
                        aVenue = venueResults.First(v => v.VenueID == venueId);
                    }
                    else if (fqlEvent.venue.Count > 0)
                    {
                        aVenue = GetVenueFromJsonObject((JsonObject)fqlEvent.venue);
                        if (aVenue == null)
                        {
                          // If no facebook page exists for this Venue, create a new negative ID
                          // All negative ID's therefore show that the Venue does not exist on Facebook
                                                    aVenue = new Venue();
                          using (RaveRadarContext _db = new RaveRadarContext())
                          {
                              long dbMin = _db.Venues.Min(v => v.VenueID).GetValueOrDefault(0);
                              long syncMin = venueResults.Min(v => v.VenueID).GetValueOrDefault(0);
                              aVenue.VenueID = (dbMin <= syncMin ? dbMin : syncMin) - 1;
                                                            aVenue.Name = fqlEvent.location ?? string.Empty;
                                                            aVenue.GetLocationFromGoogle(fqlEvent.location ?? string.Empty);

                                                            // If no location found, reset venue to null
                                                            if (aVenue.GetLocation() == null)
                                                            {
                                                                aVenue = null;
                                                            }
                          }
                        }

                                                if (aVenue != null)
                                                {
                                                    venueResults.Add(aVenue);
                                                }
                    }

                    // Before querying for the Rave, make sure we haven't already queried it
                    if (raveResults.Any(r => r.RaveID == eventId))
                    {
                        aRave = raveResults.First(r => r.RaveID == eventId);
                    }
                    else
                    {
                        aRave = new Rave();
                        aRave.RaveID = eventId ?? 0; // Should never happen
                        aRave.OwnerID = aOwner.OwnerID;
                        if (aVenue == null) { aRave.VenueID = null; } else { aRave.VenueID = aVenue.VenueID; }
                        aRave.Name = fqlEvent.name ?? string.Empty;
                        aRave.PicURL = fqlEvent.pic_square ?? ConfigurationManager.AppSettings["DefaultRaveIcon"].ToString();

                        aRave.StartTime = ConvertFacebookDateToLocal(fqlEvent.start_time, fqlEvent.is_date_only);
                        if (fqlEvent.end_time == null) { aRave.EndTime = null; }
                        else { aRave.EndTime = ConvertFacebookDateToLocal(fqlEvent.end_time, fqlEvent.is_date_only); }
                        aRave.IsDateOnly = fqlEvent.is_date_only;
                        aRave.Location = fqlEvent.location ?? string.Empty;
                        aRave.IsApproved = (aOwner == null ? false : aOwner.IsTrusted);
                        aRave.SubmitterID = null;
                        aRave.UpdateTime = DateTimeConvertor.FromUnixTime((double)fqlEvent.update_time);
                        raveResults.Add(aRave);
                    }
                }

                // Put all the details together to create one object
                eventResults.Add(new RaveDetails(aRave, aOwner, aVenue));
            }

            return eventResults;
        }
开发者ID:AndrewCraswell,项目名称:rave-radar,代码行数:98,代码来源:FQLToObjectsHelper.cs

示例11: Collapse


//.........这里部分代码省略.........
                                .Where(output => output.Item3.Item2 == outerNode)
                                .Select(
                                    output =>
                                    new
                                    {
                                        InnerNodeInputSender = output.Item1,
                                        OuterNodeInPortData = output.Item3.Item1
                                    }).ToList();

                            nodeInputs.ForEach(_ => node.AddInput());

                            node.NodeUI.RegisterAllPorts();

                            dynSettings.Bench.WorkBench.UpdateLayout();

                            return new
                            {
                                OuterNode = outerNode,
                                InnerNode = node,
                                Outputs = inputs.Where(input => input.Item3.Item2 == outerNode)
                                                .Select(input => input.Item3.Item1),
                                Inputs = nodeInputs,
                                OuterNodePortDataList = inPortsConnected
                            };
                        }).ToList();

            #endregion

            #region UI Positioning Calculations

            double avgX = selectedNodeSet.Average(node => Canvas.GetLeft(node.NodeUI));
            double avgY = selectedNodeSet.Average(node => Canvas.GetTop(node.NodeUI));

            double leftMost = selectedNodeSet.Min(node => Canvas.GetLeft(node.NodeUI)) + 24;
            double topMost = selectedNodeSet.Min(node => Canvas.GetTop(node.NodeUI));
            double rightMost = selectedNodeSet.Max(node => Canvas.GetLeft(node.NodeUI) + node.NodeUI.Width);

            #endregion

            #region Move selection to new workspace

            var connectors = new HashSet<dynConnector>(
                currentWorkspace.Connectors.Where(
                    conn => selectedNodeSet.Contains(conn.Start.Owner.NodeLogic)
                            && selectedNodeSet.Contains(conn.End.Owner.NodeLogic)));

            //Step 2: move all nodes to new workspace
            //  remove from old
            currentWorkspace.Nodes.RemoveAll(selectedNodeSet.Contains);
            currentWorkspace.Connectors.RemoveAll(connectors.Contains);

            //  add to new
            newNodeWorkspace.Nodes.AddRange(selectedNodeSet);
            newNodeWorkspace.Connectors.AddRange(connectors);

            double leftShift = leftMost - 250;
            foreach (dynNodeUI node in newNodeWorkspace.Nodes.Select(x => x.NodeUI))
            {
                Canvas.SetLeft(node, Canvas.GetLeft(node) - leftShift);
                Canvas.SetTop(node, Canvas.GetTop(node) - topMost + 120);
            }

            #endregion

            #region Insert new node into the current workspace
开发者ID:hippo811028,项目名称:Dynamo,代码行数:66,代码来源:NodeCollapser.cs

示例12: HashSetExtensions_Min_ThrowsExceptionIfHashSetIsEmpty

        public void HashSetExtensions_Min_ThrowsExceptionIfHashSetIsEmpty()
        {
            var set = new HashSet<Int32>();

            set.Min();
        }
开发者ID:prshreshtha,项目名称:ultraviolet,代码行数:6,代码来源:HashSetExtensionsTest.cs

示例13: ConvertToAst

        List<ILNode> ConvertToAst(List<ByteCode> body, HashSet<ExceptionHandler> ehs)
        {
            List<ILNode> ast = new List<ILNode>();

            while (ehs.Any()) {
                ILTryCatchBlock tryCatchBlock = new ILTryCatchBlock();

                // Find the first and widest scope
                int tryStart = ehs.Min(eh => eh.TryStart.Offset);
                int tryEnd   = ehs.Where(eh => eh.TryStart.Offset == tryStart).Max(eh => eh.TryEnd.Offset);
                var handlers = ehs.Where(eh => eh.TryStart.Offset == tryStart && eh.TryEnd.Offset == tryEnd).ToList();

                // Cut all instructions up to the try block
                {
                    int tryStartIdx;
                    for (tryStartIdx = 0; body[tryStartIdx].Offset != tryStart; tryStartIdx++);
                    ast.AddRange(ConvertToAst(body.CutRange(0, tryStartIdx)));
                }

                // Cut the try block
                {
                    HashSet<ExceptionHandler> nestedEHs = new HashSet<ExceptionHandler>(ehs.Where(eh => (tryStart <= eh.TryStart.Offset && eh.TryEnd.Offset < tryEnd) || (tryStart < eh.TryStart.Offset && eh.TryEnd.Offset <= tryEnd)));
                    ehs.ExceptWith(nestedEHs);
                    int tryEndIdx;
                    for (tryEndIdx = 0; tryEndIdx < body.Count && body[tryEndIdx].Offset != tryEnd; tryEndIdx++);
                    tryCatchBlock.TryBlock = new ILBlock(ConvertToAst(body.CutRange(0, tryEndIdx), nestedEHs));
                }

                // Cut all handlers
                tryCatchBlock.CatchBlocks = new List<ILTryCatchBlock.CatchBlock>();
                foreach(ExceptionHandler eh in handlers) {
                    int startIndex;
                    for (startIndex = 0; body[startIndex].Offset != eh.HandlerStart.Offset; startIndex++);
                    int endInclusiveIndex;
                    // Note that the end(exclusiove) instruction may not necessarly be in our body
                    for (endInclusiveIndex = 0; body[endInclusiveIndex].Next.Offset != eh.HandlerEnd.Offset; endInclusiveIndex++);
                    int count = 1 + endInclusiveIndex - startIndex;
                    HashSet<ExceptionHandler> nestedEHs = new HashSet<ExceptionHandler>(ehs.Where(e => (eh.HandlerStart.Offset <= e.TryStart.Offset && e.TryEnd.Offset < eh.HandlerEnd.Offset) || (eh.HandlerStart.Offset < e.TryStart.Offset && e.TryEnd.Offset <= eh.HandlerEnd.Offset)));
                    ehs.ExceptWith(nestedEHs);
                    List<ILNode> handlerAst = ConvertToAst(body.CutRange(startIndex, count), nestedEHs);
                    if (eh.HandlerType == ExceptionHandlerType.Catch) {
                        tryCatchBlock.CatchBlocks.Add(new ILTryCatchBlock.CatchBlock() {
                            ExceptionType = eh.CatchType,
                            Body = handlerAst
                        });
                    } else if (eh.HandlerType == ExceptionHandlerType.Finally) {
                        tryCatchBlock.FinallyBlock = new ILBlock(handlerAst);
                    } else {
                        // TODO
                    }
                }

                ehs.ExceptWith(handlers);

                ast.Add(tryCatchBlock);
            }

            // Add whatever is left
            ast.AddRange(ConvertToAst(body));

            return ast;
        }
开发者ID:HEskandari,项目名称:ILSpy,代码行数:62,代码来源:ILAstBuilder.cs

示例14: Collapse


//.........这里部分代码省略.........
                                                output =>
                                                    new
                                                    {
                                                        InnerNodeInputSender = output.Item1,
                                                        OuterNodeInPortData = output.Item3.Item1
                                                    })
                                            .ToList();

                                    nodeInputs.ForEach(_ => node.AddInput());

                                    node.RegisterAllPorts();

                                    return
                                        new
                                        {
                                            OuterNode = outerNode,
                                            InnerNode = node,
                                            Outputs =
                                                inputs.Where(
                                                    input => input.Item3.Item2 == outerNode)
                                                    .Select(input => input.Item3.Item1),
                                            Inputs = nodeInputs,
                                            OuterNodePortDataList = inPortsConnected
                                        };
                                }).ToList();

                #endregion

                #region UI Positioning Calculations

                double avgX = selectedNodeSet.Average(node => node.X);
                double avgY = selectedNodeSet.Average(node => node.Y);

                double leftMost = selectedNodeSet.Min(node => node.X);
                double topMost = selectedNodeSet.Min(node => node.Y);
                double rightMost = selectedNodeSet.Max(node => node.X + node.Width);

                #endregion

                #region Handle full selected connectors

                // Step 2: Determine all the connectors whose start/end owners are 
                // both in the selection set, and then move them from the current 
                // workspace into the new workspace.

                var fullySelectedConns =
                    new HashSet<ConnectorModel>(
                        currentWorkspace.Connectors.Where(
                            conn =>
                            {
                                bool startSelected = selectedNodeSet.Contains(conn.Start.Owner);
                                bool endSelected = selectedNodeSet.Contains(conn.End.Owner);
                                return startSelected && endSelected;
                            }));

                foreach (var ele in fullySelectedConns)
                {
                    undoRecorder.RecordDeletionForUndo(ele);
                    currentWorkspace.Connectors.Remove(ele);
                }

                #endregion

                #region Handle partially selected connectors

                // Step 3: Partially selected connectors (either one of its start 
开发者ID:whztt07,项目名称:Dynamo,代码行数:67,代码来源:NodeCollapser.cs

示例15: AStarSearch

        // Returns a stack of nodes representing the path from start to goal.
        // Popping elements off the stack yields the correct sequence of moves
        // in order.
        public Stack<MazeNode> AStarSearch(MazeNode start, MazeNode goal)
        {
            HashSet<MazeNode> closed = new HashSet<MazeNode>();
            HashSet<MazeNode> open = new HashSet<MazeNode>();
            MazeNode current;
            ArrayList children;
            int GScoreEstimate;
            start.g = 0;
            start.h = start.manhattanDistance(goal);
            start.f = start.g + start.h;
            start.a_star_parent = start;
            open.Add(start);

            //While there are adjacent, unexplored nodes to search
            while (open.Count > 0)
            {
                current = open.Min();
                //If we've reached our goal
                if (current == goal)
                {
                    //Retrieve the path we took via a stack
                    Stack<MazeNode> path_to_goal = new Stack<MazeNode>();
                    while (current.a_star_parent != current)
                    {
                        path_to_goal.Push(current);
                        current = current.a_star_parent;
                    }
                    path_to_goal.Push(current);
                    return path_to_goal;
                }

                //Else continue our search
                open.Remove(current);
                closed.Add(current);
                children = current.getAdjacentEdges();
                foreach (MazeNode child in children)
                {
                    // If we've visited this node already, skip it.
                    if (closed.Contains(child))
                    {
                        continue;
                    }

                    // g is computed as the cost it took us to get here, plus the distance between the
                    // current node and the child we're considering.
                    GScoreEstimate = (int)(current.g) + current.manhattanDistance(child);

                    // If we haven't considered this node already, or our current estimate is more optimistic
                    // than our prior estimation
                    if (!open.Contains(child) || GScoreEstimate < child.g)
                    {
                        child.g = GScoreEstimate;
                        child.f = child.g + child.manhattanDistance(goal);

                        if (!open.Contains(child))
                        {
                            open.Add(child);
                        }

                        child.a_star_parent = current;
                    }
                }
                closed.Add(current);
            }
            //Search failed, no more nodes to find on open list
            return null;
        }
开发者ID:bennuttle,项目名称:Maize,代码行数:70,代码来源:MazeGraph.cs


注:本文中的HashSet.Min方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。