本文整理汇总了C#中System.Collections.Generic.PriorityQueue.Add方法的典型用法代码示例。如果您正苦于以下问题:C# PriorityQueue.Add方法的具体用法?C# PriorityQueue.Add怎么用?C# PriorityQueue.Add使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.Collections.Generic.PriorityQueue
的用法示例。
在下文中一共展示了PriorityQueue.Add方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: distance
public static int distance(bool[,] passable, int startX, int startY, int goalX, int goalY)
{
int[,] distanceMatrix = new int[passable.GetLength(0), passable.GetLength(1)];
for (int i = 0; i < distanceMatrix.GetLength(0); i++)
{
for (int j = 0; j < distanceMatrix.GetLength(1); j++)
{
distanceMatrix[i, j] = -1;
}
}
distanceMatrix[startX, startY] = 0;
PriorityQueue<Node> openSet = new PriorityQueue<Node>();
Node initial = new Node(startX, startY, 0, euclideanDistance(startX, startY, goalX, goalY));
openSet.Add(initial);
while (true)
{
if (openSet.IsEmpty())
{
// we failed to find the goal
return -1;
}
Node current = openSet.PopFront();
if (current.x == goalX && current.y == goalY)
{
// we found it!
return current.costToGetHere;
}
// search all the neighbours
List<Node> neighbours = current.generateNeighbours(passable, distanceMatrix, goalX, goalY);
openSet.AddRange(neighbours);
}
}
示例2: Search
public static SearchResult Search(AbstractNode initialNode, IKnowledgeBase kb)
{
var frontier = new PriorityQueue<AbstractNode>();
var explored = new List<AbstractState>();
var statesSearched = 0; //Bliver kun brugt af os af ren interesse
var end = initialNode.Target;
frontier.Add(initialNode);
explored.Add(initialNode.State);
while (frontier.Count > 0)
{
// Chooses the lowest-cost node in the frontier
var currentNode = frontier.Pop();
statesSearched++;
if (currentNode.State.Equals(end))
return new SearchResult(currentNode, statesSearched, true);
var actions = kb.ActionsForNode(currentNode);
//Explore /expand the current node
foreach (var action in actions)
{
var child = kb.Resolve(currentNode, action, end);
//System.Console.WriteLine("Frontier.Count: " + frontier.Count);
if (!explored.Contains(child.State) && !frontier.Contains(child))
{
explored.Add(child.State);
frontier.Add(child);
}
else if(true)
{
for (int i = 0; i < frontier.Count; i++)
{
var frontierNode = frontier[i];
if (frontierNode.State.Equals(child.State) && frontierNode.PathCost > child.PathCost)
{
frontier[i] = child;
break;
}
}
}
}
}
return new SearchResult(null, statesSearched, false);
}
示例3: findPath
public static Path findPath(Node startNode, Node destination)
{
List<Node> closedList = new List<Node>();
PriorityQueue<Node> openList = new PriorityQueue<Node>();
Dictionary<Node, int> gScore = new Dictionary<Node,int>();
gScore[startNode] = 0;
Dictionary<Node, int> fScore = new Dictionary<Node,int>();
fScore[startNode] = startNode.HeuristicDistance(destination);
Dictionary<Node, Node> prevNode = new Dictionary<Node, Node>();
openList.Add(fScore[startNode], startNode);
while (openList.Count > 0)
{
Node current = openList.RemoveMin();
if (current.Equals(destination))
{
return getPath(prevNode, destination);
}
else
{
closedList.Add(current);
Node[] neighbours = current.GetNeighbours();
foreach (Node next in neighbours)
{
if (closedList.Contains(next))
continue;
int newGScore = gScore[current] + current.distanceBetween(next);
if (!openList.Contains(next) || newGScore < gScore[next])
{
prevNode[next] = current;
gScore[next] = newGScore;
fScore[next] = gScore[next] + next.HeuristicDistance(destination);
if (!openList.Contains(next))
openList.Add(fScore[next], next);
}
}
}
}
return null;
}
示例4: AStar
public List<Vector2> AStar(Vector2 startPosition, Vector2 targetPosition)
{
DNode2 startNode = graph.GetNode(startPosition);
DNode2 targetNode = graph.GetNode(targetPosition);
List<Vector2> positions = new List<Vector2>();
PriorityQueue<DNode2> pq = new PriorityQueue<DNode2>();
foreach (DNode2 d in graph.adjList.Keys)
{
d.Weight = 9999999;
pq.Add(d);
}
startNode.Weight = 0;
while (!pq.Empty())
{
DNode2 n = pq.Remove();
positions.Add(n.Coords);
if (n.Coords == targetPosition + new Vector2(80, 80))
{
positions.TrimExcess();
return positions;
}
foreach (Edge e in graph.adjList[n])
{
DNode2 z = e.GetOpposite(n);
double r = e.Weight + Vector2.Distance(z.Coords, targetPosition);
if (r < z.Weight)
{
z.Weight = r;
try
{
pq.Remove(z);
}
catch (ArgumentException)
{
continue;
}
pq.Add(z);
}
}
}
return positions;
}
示例5: AStarSearch
public void AStarSearch(Vector2 sourcePoint, Vector2 destinationPoint, out Vector2 nextNode)
{
//Console.WriteLine("Going from (" + sourcePoint.X + ", " + sourcePoint.Y + ") to (" + destinationPoint.X + ", " + destinationPoint.Y + ")");
Node source = adjacencyList[(int)(columns * sourcePoint.X + sourcePoint.Y)];
Node destination = adjacencyList[(int)(columns * destinationPoint.X + destinationPoint.Y)];
PriorityQueue <Node> Q = new PriorityQueue<Node>();
source.Distance = 0;
Q.Add(source.Priority, source);
while (Q.Count > 0)
{
Node current = Q.RemoveMin();
if (current == destination)
{
Node pathParent = current.Parent;
Stack<Node> path = new Stack<Node>();
path.Push(current);
while (pathParent != null)
{
path.Push(pathParent);
pathParent = pathParent.Parent;
}
Thread t = new Thread(new ParameterizedThreadStart(DrawPath));
t.Start(path);
path.Pop();
nextNode = new Vector2(path.Peek().X * 32, path.Peek().Y * 32);
return;
}
List<Node> allAdjacent = new List<Node>();
allAdjacent.AddRange(current.AdjacentNodes);
allAdjacent.AddRange(current.CornerNodes);
foreach (Node n in allAdjacent)
{
Node node = adjacencyList[columns * n.X + n.Y];
if (node.Distance == int.MaxValue)
{
node.Distance = current.Distance + 1;
node.Parent = current;
node.Visited = true;
node.Priority = (int)(destinationPoint - sourcePoint).Length() + node.Distance;
Q.Add(node.Priority, node);
}
}
}
nextNode = new Vector2(-1);
}
示例6: AddMax
public void AddMax()
{
PriorityQueue<int> q = new PriorityQueue<int>((i, j) => j.CompareTo(i));
q.Storage = new List<int> { 11, 5, 8, 3, 4 };
q.Add(15);
Assert.AreEqual(6, q.Storage.Count);
Assert.AreEqual(15, q.Storage[0]);
Assert.AreEqual(11, q.Storage[2]);
Assert.AreEqual(8, q.Storage[5]);
}
示例7: Search
public static int Search(List<State> states, List<Action> actions, State start, Tile target)
{
var found = 0;
PriorityQueue<BFNode> frontier = new PriorityQueue<BFNode>();
List<State> explored = new List<State>();
frontier.Add(new BFNode(start));
while (frontier.Count > 0)
{
// Chooses the lowest-cost node in the frontier
BFNode currentBFNode = frontier.Pop();
// Win condition
if (currentBFNode.State.Type.Equals(target))
found++;
explored.Add(currentBFNode.State);
// Filter actions to the ones connected to the current node
foreach (Action action in actions.Where(a => a.StateA.Equals(currentBFNode.State)))
{
// One of A or B will be the currentBFNode's action
// but it won't be added to the frontier since it
// is already in explored
var childA = new BFNode(currentBFNode, action, action.StateA);
var childB = new BFNode(currentBFNode, action, action.StateB);
if (!explored.Contains(childA.State) && !frontier.Any(n => n.State == childA.State))
frontier.Add(childA);
if (!explored.Contains(childB.State) && !frontier.Any(n => n.State == childB.State))
frontier.Add(childB);
}
}
return found;
}
示例8: AddMin
public void AddMin()
{
PriorityQueue<int> q = new PriorityQueue<int>((i, j) => i.CompareTo(j));
q.Storage = new List<int> { 4, 4, 8, 9, 4, 12, 9, 11, 13 };
q.Add(7);
Assert.AreEqual(10, q.Storage.Count);
Assert.AreEqual(7, q.Storage[9]);
q.Add(10);
Assert.AreEqual(11, q.Storage.Count);
Assert.AreEqual(10, q.Storage[10]);
q.Add(5);
Assert.AreEqual(12, q.Storage.Count);
Assert.AreEqual(5, q.Storage[2]);
Assert.AreEqual(8, q.Storage[5]);
Assert.AreEqual(12, q.Storage[11]);
}
示例9: Search
public static INode Search(List<State> states, List<Action> actions, State start, State end)
{
PriorityQueue<Node> frontier = new PriorityQueue<Node>();
List<State> explored = new List<State>();
frontier.Add(new Node(start, end));
while (frontier.Count > 0)
{
// Chooses the lowest-cost node in the frontier
Node currentNode = frontier.Pop();
// Win condition
if (currentNode.State.Equals(end))
return currentNode;
// Add currentNode to list of explored
explored.Add(currentNode.State);
// Filter actions to the ones connected to the current node
foreach (Action action in actions.Where(a => a.StateA.Equals(currentNode.State) || a.StateB.Equals(currentNode.State)))
{
// One of A or B will be the currentNode's action
// but it won't be added to the frontier since it
// is already in explored
var childA = new Node(currentNode, action, action.StateA, end);
if (!explored.Contains(childA.State))
frontier.Add(childA);
var childB = new Node(currentNode, action, action.StateB, end);
if (!explored.Contains(childB.State))
frontier.Add(childB);
}
}
return null;
}
示例10: GetHeap
public PriorityQueue<Pattern> GetHeap()
{
if (subPatternCheck)
{
PriorityQueue<Pattern> ret = new PriorityQueue<Pattern>(maxSize);
foreach (Pattern p in queue)
{
if (patternIndex[p.Support].Contains(p))
{
ret.Add(p);
}
}
return ret;
}
return queue;
}
示例11: runDijstra
public List<Point> runDijstra()
{
foreach (KeyValuePair<Point, List<Point>> pair in adjList)
{
dist[pair.Key] = 10000000;
visited[pair.Key] = false;
prev[pair.Key] = new Point(-1,-1);
}
dist[start] = 0;
PriorityQueue<dijkstraPoint> queue = new PriorityQueue<dijkstraPoint>();
queue.Add(new dijkstraPoint(start));
while (queue.Count>0)
{
dijkstraPoint u = queue.Dequeue();
visited[u.point] = true;
foreach (Point v in adjList[u.point])
{
int alt = dist[u.point] + (int)Utilities.distance(u.point, v);
if (alt < dist[v])
{
dist[v] = alt;
prev[v] = u.point;
if (!visited[v])
queue.Enqueue(new dijkstraPoint(v));
}
}
}
if (dist[dest] == 10000000)
return null;
List<Point> path = new List<Point>();
Point curr = dest;
while (curr != new Point(-1, -1))
{
path.Add(curr);
curr = prev[curr];
}
path.Reverse();
return path;
}
示例12: TestWithPrimitiveType
public void TestWithPrimitiveType()
{
var priorityQueueInts = new PriorityQueue<int>();
priorityQueueInts.Add(5);
priorityQueueInts.Add(10);
priorityQueueInts.Add(-5);
priorityQueueInts.Add(1);
priorityQueueInts.Add(13);
priorityQueueInts.Add(13);
priorityQueueInts.Add(0);
priorityQueueInts.Add(25);
var numbersActualOrder = new List<int>();
while (priorityQueueInts.Count > 0)
{
numbersActualOrder.Add(priorityQueueInts.RemoveFirst());
}
var numbersExpectedOrder = new List<int>() { -5, 0, 1, 5, 10, 13, 13, 25 };
CollectionAssert.AreEqual(numbersExpectedOrder, numbersActualOrder);
}
示例13: Find
/// <summary>
/// For given 'center' point returns a subset of 'm' stored points that are
/// closer to the center than others.
///
/// E.g. Stored: (0, 1) (0, 2) (0, 3) (0, 4) (0, 5)
///
/// Find(new Point(0, 0), 3) -> (0, 1), (0, 2), (0, 3)
///
/// Seems like we can do this in two ways
///
/// Quick select - as we do quick sort on distance from center point,
/// stop is pivot index == m, then everything on left is closest m
/// complexity will be n log n
///
/// Max - Heap - reprocess the points into a max - heap with bounded size of m
/// Since everything in heap is smaller than max value, this will also ensure we
/// get m closet points. complexity will be n log m
/// </summary>
/// <param name="point"></param>
/// <param name="k"></param>
public static List<int[]> Find(List<int[]> points, int[] centerPoint, int m)
{
PriorityQueue<int[]> maxHeap = new PriorityQueue<int[]>((i, j) =>
//since this is a max heap, we want to compare j against i
//and we are comparing distance (sqrt(x^2 + y^2)) from the point
(System.Math.Pow(j[0] - centerPoint[0], 2) + System.Math.Pow(j[1] - centerPoint[1], 2))
.CompareTo(System.Math.Pow(i[0] - centerPoint[0], 2) + System.Math.Pow(i[1] - centerPoint[1], 2))
);
foreach(int[] point in points) {
maxHeap.Add(point);
if (maxHeap.Storage.Count > m)
{
maxHeap.ExtractRoot();
}
}
List<int[]> result = new List<int[]>();
while(maxHeap.Storage.Count > 0)
{
result.Add(maxHeap.ExtractRoot());
}
return result;
}
示例14: Main
static void Main(string[] args)
{
// ------------------- Variable Declarations
string inputText = ""; // text to be encoded and decoded.
// ------------------- Input
Console.Write("Enter a string to be huffman encoded: ");
inputText = Console.ReadLine();
Console.WriteLine("The text you entered is: \"{0}\"", inputText);
// ------------------- Processing
// Group the characters into a collection of Keys (the characters) and Counts (frequencies)
var aggregatedCharacters = inputText.GroupBy(character => character).Select(group => new { character = group.Key, frequency = group.Count() });
// Priority Queue of HuffmanNodes of CharFreqPairs
var charFreqPriorityQueue = new PriorityQueue<HuffmanNode<CharFreqPair>>(aggregatedCharacters.Count());
// Add the Character:Frequency pairs to the Priority Queue
foreach (var aggregatedCharacter in aggregatedCharacters)
charFreqPriorityQueue.Add(new HuffmanNode<CharFreqPair>(new CharFreqPair(aggregatedCharacter.frequency, aggregatedCharacter.character)));
// Create HuffmanTree object
var huffmanTree = new HuffmanTree(charFreqPriorityQueue);
string testing = huffmanTree.EncodeText(inputText);
Console.WriteLine("The encoded text is: \"{0}\"", testing);
testing = huffmanTree.DecodeText(testing);
Console.WriteLine("The decoded text is: \"{0}\"", testing);
//huffmanTree.Print();
// Pause before exiting
Console.WriteLine("Press return to exit...");
Console.ReadLine();
}
示例15: TestWithClassHumanImplementsIComparableByAge
public void TestWithClassHumanImplementsIComparableByAge()
{
// Test with class Human implements IComparable (by Age):
var priorityQueueHumans = new PriorityQueue<Human>();
priorityQueueHumans.Add(new Human("Ivan", 25));
priorityQueueHumans.Add(new Human("Georgi", 13));
priorityQueueHumans.Add(new Human("Cvetelina", 18));
priorityQueueHumans.Add(new Human("Plamena", 22));
priorityQueueHumans.Add(new Human("Gergana", 23));
priorityQueueHumans.Add(new Human("Qna", 21));
var numbersActualOrder = new List<string>();
while (priorityQueueHumans.Count > 0)
{
numbersActualOrder.Add(priorityQueueHumans.RemoveFirst().Name);
}
var numbersExpectedOrder = new List<string>() { "Georgi", "Cvetelina", "Qna", "Plamena", "Gergana", "Ivan" };
CollectionAssert.AreEqual(numbersExpectedOrder, numbersActualOrder);
}