public Huffman(IEnumerable<KeyValuePair<char, int>> kvps) { //保存原始数据 var tmpOriginalNodes = from kvp in kvps select new HuffmanNode(kvp.Key, kvp.Value); //创建最小优先队列,并输入数据 MinPriorityQueue<HuffmanNode> minQueue = new MinPriorityQueue<HuffmanNode>(); originalNodes = new List<HuffmanNode>(); foreach (var node in tmpOriginalNodes) { originalNodes.Add(node); minQueue.Insert(node); } //建造编码树,并取得编码树的根节点 while (!minQueue.IsEmpty) { HuffmanNode left = minQueue.ExtractMin(); if (minQueue.IsEmpty) { rootNode = left; break; } HuffmanNode right = minQueue.ExtractMin(); HuffmanNode newNode = new HuffmanNode(null, left.Value + right.Value, left, right); left.Parent = newNode; right.Parent = newNode; minQueue.Insert(newNode); } }
static void Main(string[] args) { MaxPriorityQueue<IHeapValue> maxheap = new MaxPriorityQueue<IHeapValue>(); MinPriorityQueue<IHeapValue> minheap = new MinPriorityQueue<IHeapValue>(); List<IHeapValue> list = new List<IHeapValue>(); Random rnd = new Random(DateTime.Now.Millisecond); for (int i = 0; i < 10; i++) { HeapNode hn = new HeapNode() { Value = rnd.Next(0, 100) }; list.Add(hn); maxheap.Insert(hn); minheap.Insert(hn); } Console.WriteLine("RandomData:"); list.ForEach(n => Console.Write("{0},", n.Value)); Console.WriteLine(Environment.NewLine + "MaxHeapOutput:"); while (!maxheap.IsEmpty) { Console.Write("{0},", maxheap.ExtractMax().Value); } Console.WriteLine(Environment.NewLine + "MinHeapOutput:"); while (!minheap.IsEmpty) { Console.Write("{0},", minheap.ExtractMin().Value); } Console.ReadKey(); }
public Prim(AdjacencyListGraph g) { //initialize the various arrays and the minimum priority queue _edgeTo = new Edge[g.VerticesCount+1]; _distTo = new double[g.VerticesCount+1]; _marked = new bool[g.VerticesCount+1]; _pq = new MinPriorityQueue<double>(g.VerticesCount); //for each edge in the minimum spanning tree set the weight equal to infinity for (var v = 0; v < g.VerticesCount; v++) _distTo[v] = double.PositiveInfinity; for (var v = 0; v < g.VerticesCount; v++) if (!_marked[v]) Run(g, v); }
/// <summary> /// Build huffman tree from given priority queue /// </summary> /// <param name="q"></param> /// <returns></returns> private BinaryTreeNode<byte> BuildHuffmanTree(MinPriorityQueue<long,BinaryTreeNode<byte>> q) { while(q.Count>1) { // Get and remove the two smallest priorities and their associated trees long temp1 = q.MininumPriority; BinaryTreeNode<byte> tree1 = q.RemoveMinimumPriority(); long temp2 = q.MininumPriority; BinaryTreeNode<byte> tree2 = q.RemoveMinimumPriority(); // Construct a new binary tree with these trees as its children and 0 as its data (which will be unused). BinaryTreeNode<byte> newBinTree = new BinaryTreeNode<byte>(0,tree1,tree2); // Add the resulting tree to the min-priority queue with a priority equal to the sum of the priorities of its children. q.Add(newBinTree, temp1+temp2); } return q.RemoveMinimumPriority(); }
public void MinPriorityQueue_Enqueue() { int capacity = 5; var q = new MinPriorityQueue<Element>(capacity); for (int i = capacity; i > 0; i--) { q.Enqueue(new Element { Number = i, Data = new byte[i]}); } Assert.IsTrue(q.Size == capacity); for (int i = 1; i <= capacity; i++) { var e = q.Dequeue(); Assert.IsTrue(i == e.Number); } }
/// <summary> /// Builds a Huffman tree out of the given frequencies. /// </summary> /// <param name="freq">Array of frequencies for a byte at index of byte</param> /// <param name="numberOfNodes">Returns number of nodes in Huffman tree</param> /// <returns>A fully loaded Huffman tree.</returns> private BinaryTreeNode<byte> BuildHuffmanTree(long[] freq, out int numberOfNodes) { MinPriorityQueue<BinaryTreeNode<byte>> pq = new MinPriorityQueue<BinaryTreeNode<byte>>(); int count = 0; for (int i = 0; i < freq.Length; i++) { if (freq[i] != 0) { BinaryTreeNode<byte> tmp = new BinaryTreeNode<byte>(); tmp.RootValue = (byte)i; pq.AddElement(tmp, freq[i]); } } while (pq.Count > 1) { BinaryTreeNode<byte> root = new BinaryTreeNode<byte>(); root.IsEmpty = false; int weight1 = (int)pq.LowestPriority; BinaryTreeNode<byte> child1 = pq.RemoveLowestPriority(); child1.IsEmpty = false; int weight2 = (int)pq.LowestPriority; BinaryTreeNode<byte> child2 = pq.RemoveLowestPriority(); child2.IsEmpty = false; root.LeftChild = child1; root.RightChild = child2; pq.AddElement(root, weight1 + weight2); count++; } numberOfNodes = count + 1; BinaryTreeNode<byte> huf = pq.RemoveLowestPriority(); return huf; }
public static int Run(int[] nums, int k) { var pq = new MinPriorityQueue(k); for (int i = 0; i < k; ++i) { pq.Insert(nums[i]); } for (int i = k; i < nums.Length; ++i) { if (nums[i] > pq.Peek()) { pq.Pop(); pq.Insert(nums[i]); } } return(pq.Pop()); }
public void MinPQ_Basic() { var pq = new MinPriorityQueue<int>(); pq.Insert(2, null); pq.Insert(6, null); pq.Insert(1, null); Assert.AreEqual(1, (int)(pq.DelMax().Item1)); pq.Insert(9, null); pq.Insert(7, null); pq.Insert(1, null); Assert.AreEqual(1, (int)(pq.DelMax().Item1)); pq.Insert(2, null); pq.Insert(6, null); pq.Insert(1, null); Assert.AreEqual(1, (int)(pq.DelMax().Item1)); Assert.AreEqual(2, (int)(pq.Max().Item1)); Assert.AreEqual(2, (int)(pq.DelMax().Item1)); Assert.AreEqual(2, (int)(pq.DelMax().Item1)); Assert.AreEqual(6, (int)(pq.DelMax().Item1)); }
public void MinPriorityQueueTest_InitWithKey() { int[] a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; Shuffle.Do(a); MinPriorityQueue <int> pq = new MinPriorityQueue <int>(a); Assert.IsFalse(pq.IsEmpty()); Assert.AreEqual(10, pq.Size()); for (int i = 0; i < 10; i++) { int result = pq.Min(); Assert.AreEqual(i, result); result = pq.DelMin(); Assert.AreEqual(i, result); } Assert.IsTrue(pq.IsEmpty()); Assert.AreEqual(0, pq.Size()); }
public Dijkstra(IGraph graph) { // verifica peso negativo foreach (var edge in graph.Edges()) { if (edge.Weight < 0) throw new Exception($"edge {edge} has negative weight"); } // inicializa os arrays _distanceTo = new double[graph.VerticesCount + 1]; _edgeTo = new Edge[graph.VerticesCount + 1]; for (var i = 0; i < graph.VerticesCount; i++) { _distanceTo[i] = double.PositiveInfinity; } _priorityQueue = new MinPriorityQueue<double>(graph.VerticesCount+1); _graph = graph; }
public void MinPriorityQueueDoesInsertItemInCollectionAsHeadIfItemIsLowerPriorityThanOriginalHead() { var priorityQueue = new MinPriorityQueue <string, int>(50); List <Tuple <string, int> > items = new List <Tuple <string, int> > { new Tuple <string, int>("A_50", 50), new Tuple <string, int>("A_41", 41), new Tuple <string, int>("A_38", 38), new Tuple <string, int>("A_37", 37), new Tuple <string, int>("A_23", 23), new Tuple <string, int>("A_11", 11), new Tuple <string, int>("A_5", 5), new Tuple <string, int>("A_3", 3), }.Randomize() .ToList(); priorityQueue.EnqueueRange(items); string originalHead = priorityQueue.Peek(); List <Tuple <string, int> > newItems = new List <Tuple <string, int> > { new Tuple <string, int>("A_2", 2), new Tuple <string, int>("A_4", 4), new Tuple <string, int>("A_6", 6), new Tuple <string, int>("A_8", 8), new Tuple <string, int>("A_10", 10), new Tuple <string, int>("A_12", 12), new Tuple <string, int>("A_14", 14), new Tuple <string, int>("A_16", 16), }.Randomize() .ToList(); priorityQueue.EnqueueRange(newItems); string newHead = priorityQueue.Peek(); Assert.AreEqual("A_3", originalHead); Assert.AreEqual("A_2", newHead); }
public void MaintainMinHeap() { var sut = new MinPriorityQueue <int, int>(); var random = new Random(); var sortedResults = new List <int>(); for (var i = 0; i < 50000; i++) { sortedResults.Add(random.Next(1000)); } sut.AddRange(sortedResults, x => x); sortedResults = sortedResults.OrderBy(x => x).ToList(); for (var i = 0; i < 50000; i++) { Assert.AreEqual(sut.Dequeue(), sortedResults[i]); } }
public void MinPQ_Basic() { var pq = new MinPriorityQueue <int>(); pq.Insert(2, null); pq.Insert(6, null); pq.Insert(1, null); Assert.AreEqual(1, (int)(pq.DelTop().Item1)); pq.Insert(9, null); pq.Insert(7, null); pq.Insert(1, null); Assert.AreEqual(1, (int)(pq.DelTop().Item1)); pq.Insert(2, null); pq.Insert(6, null); pq.Insert(1, null); Assert.AreEqual(1, (int)(pq.DelTop().Item1)); Assert.AreEqual(2, (int)(pq.Top().Item1)); Assert.AreEqual(2, (int)(pq.DelTop().Item1)); Assert.AreEqual(2, (int)(pq.DelTop().Item1)); Assert.AreEqual(6, (int)(pq.DelTop().Item1)); }
public Prim(AdjacencyListGraph g) { //initialize the various arrays and the minimum priority queue _edgeTo = new Edge[g.VerticesCount + 1]; _distTo = new double[g.VerticesCount + 1]; _marked = new bool[g.VerticesCount + 1]; _pq = new MinPriorityQueue <double>(g.VerticesCount); //for each edge in the minimum spanning tree set the weight equal to infinity for (var v = 0; v < g.VerticesCount; v++) { _distTo[v] = double.PositiveInfinity; } for (var v = 0; v < g.VerticesCount; v++) { if (!_marked[v]) { Run(g, v); } } }
private void MinPriorityQueueConstructorWithOrder(MinPriorityQueue <Order> pq) { Assert.True(pq.IsEmpty); var rand = new Random((int)DateTime.Now.Ticks & 0x0000ffff); var set = new TreeSet <int>(); Push(pq, set, rand, 10000); Assert.Equal(10000, pq.Count); Pop(pq, set, 6000); Assert.Equal(4000, pq.Count); Push(pq, set, rand, 20000); Assert.Equal(24000, pq.Count); Pop(pq, set, 14000); Assert.Equal(10000, pq.Count); Pop(pq, set, 5000); Assert.Equal(5000, pq.Count); Push(pq, set, rand, 1000); Assert.Equal(6000, pq.Count); Push(pq, set, rand, 1000); Assert.Equal(7000, pq.Count); }
/// <summary> /// Handles a Click event on the "Select a File" button. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void uxSelectFile_Click(object sender, EventArgs e) { if (uxOpenDialog.ShowDialog() == DialogResult.OK) { try { BinaryTreeNode <byte> t = null; // Add code to build the Huffman tree and assign it to t. long[] array = CountFrequencies(uxOpenDialog.FileName); MinPriorityQueue <long, BinaryTreeNode <byte> > leaves = BuildLeaves(array); t = GetHuffmanTree(leaves); new TreeForm(t, 100).Show(); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } }
public void MinPriorityQueueInsertsItems() { var priorityQueue = new MinPriorityQueue <string, int>(50); List <Tuple <string, int> > items = new List <Tuple <string, int> > { new Tuple <string, int>("A_50", 50), new Tuple <string, int>("A_41", 41), new Tuple <string, int>("A_38", 38), new Tuple <string, int>("A_37", 37), new Tuple <string, int>("A_23", 23), new Tuple <string, int>("A_11", 11), new Tuple <string, int>("A_5", 5), new Tuple <string, int>("A_3", 3), }.Randomize() .ToList(); priorityQueue.EnqueueRange(items); Assert.AreEqual(8, priorityQueue.Count); }
public void HandleUnsortedInput() { var sut = new MinPriorityQueue <int, int>(); var random = new Random(); for (var i = 0; i < 50000; i++) { var randomValue = random.Next(1000); sut.Enqueue(randomValue, randomValue); } var results = new List <int>(); for (var i = 0; i < 50000; i++) { results.Add(sut.Dequeue()); } var sortedResults = new List <int>(results).OrderBy(x => x).ToList(); CollectionAssert.AreEqual(sortedResults, results); }
public void MinPriorityQueue_Full_EnumeratorTest() { var testData = new int[] { 12, 0, 3, 9, 1, 10, 4, 15, 5, 2, 13, 7, 8, 6, 11, 14 }; var queue = new MinPriorityQueue <int>(); foreach (var item in testData) { queue.Enqueue(item); } Assert.IsFalse(queue.IsEmpty); Assert.AreEqual(testData.Length, queue.Size); int value = 0; foreach (var item in queue) { Assert.AreEqual(value++, item); } Assert.AreEqual(16, value); }
/// <summary> /// Finds a shortest path from the given start node to the given end node in the given graph. /// </summary> /// <param name="u">The start node.</param> /// <param name="v">The end node.</param> /// <param name="map">The graph.</param> /// <param name="paths">The resulting shortest paths.</param> /// <returns>The length of the shortest path.</returns> private decimal ShortestPath(string u, string v, DirectedGraph <string, decimal> map, out Dictionary <string, string> paths) { paths = new Dictionary <string, string>(); MinPriorityQueue <decimal, Tuple <string, string> > q = new MinPriorityQueue <decimal, Tuple <string, string> >(); paths.Add(u, u); if (u == v) { return(0); } foreach (Tuple <string, decimal> t in map.OutgoingEdges(u)) { string w = t.Item1; decimal len = t.Item2; q.Add(new Tuple <string, string>(u, w), len); } while (q.Count != 0) { decimal p = q.MininumPriority; Tuple <string, string> edge = q.RemoveMinimumPriority(); string w = edge.Item1; string x = edge.Item2; if (!paths.ContainsKey(x)) { paths.Add(x, w); if (x == v) { return(p); } foreach (Tuple <string, decimal> t in map.OutgoingEdges(x)) { string y = t.Item1; decimal len = t.Item2; q.Add(new Tuple <string, string>(x, y), p + len); } } } return(-1); }
public void EnumerateValuesMinFirst() { var sut = new MinPriorityQueue <int, int>(); var random = new Random(); var sortedResults = new List <int>(); for (var i = 0; i < 50000; i++) { var randomValue = random.Next(1000); sortedResults.Add(randomValue); sut.Enqueue(randomValue, randomValue); } sortedResults = sortedResults.OrderBy(x => x).ToList(); var j = 0; foreach (var result in sut) { Assert.AreEqual(sortedResults[j], result); j++; } }
public Dijkstra(IGraph graph) { // verifica peso negativo foreach (var edge in graph.Edges()) { if (edge.Weight < 0) { throw new Exception($"edge {edge} has negative weight"); } } // inicializa os arrays _distanceTo = new double[graph.VerticesCount + 1]; _edgeTo = new Edge[graph.VerticesCount + 1]; for (var i = 0; i < graph.VerticesCount; i++) { _distanceTo[i] = double.PositiveInfinity; } _priorityQueue = new MinPriorityQueue <double>(graph.VerticesCount + 1); _graph = graph; }
public void MinPriorityQueueClearRemovesAllItems() { var priorityQueue = new MinPriorityQueue <string, int>(50); List <Tuple <string, int> > items = new List <Tuple <string, int> > { new Tuple <string, int>("A_50", 50), new Tuple <string, int>("A_41", 41), new Tuple <string, int>("A_38", 38), new Tuple <string, int>("A_37", 37), new Tuple <string, int>("A_23", 23), new Tuple <string, int>("A_11", 11), new Tuple <string, int>("A_5", 5), new Tuple <string, int>("A_3", 3), }.Randomize() .ToList(); priorityQueue.EnqueueRange(items); priorityQueue.Clear(); Assert.IsTrue(priorityQueue.IsEmpty); }
/// <summary> /// Uses Dijkstra's Algorithm to find the shortest distance in a graph between point u and v! /// </summary> /// <param name="u"> Name of the node we are starting at </param> /// <param name="v">Name of the node that serves as our destination </param> /// <param name="map"> Map that we are sifting through to find the shortest path </param> /// <param name="paths"> Dictionary whose keys are a node, and the value is it's previous node </param> /// <returns> The shortest path in decimal form! </returns> private static decimal ShortestPath(string u, string v, DirectedGraph <string, decimal> map, out Dictionary <string, string> paths) { paths = new Dictionary <string, string>(); // String value in Edge is a node that has already been visited! // Priority is the shortest path up until the source node (string value in Edge) MinPriorityQueue <decimal, Edge <string, decimal> > queue = new MinPriorityQueue <decimal, Edge <string, decimal> >(); paths.Add(u, u); if (u == v) { return(0); } foreach (Edge <string, decimal> edge in map.OutgoingEdges(u)) { queue.Add(edge.Data, edge); } while (queue.Count != 0) { decimal minPriority = queue.MinimumPriority; Edge <string, decimal> nextEdge = queue.RemoveMinimumPriority(); if (paths.ContainsKey(nextEdge.Destination) == false) { paths.Add(nextEdge.Destination, nextEdge.Source); if (nextEdge.Destination == v) { return(minPriority); } foreach (Edge <string, decimal> edge in map.OutgoingEdges(nextEdge.Destination)) { //queue.Add(edge.Data, edge); queue.Add(minPriority + edge.Data, edge); } } } return(-1); }
public void MinPriorityQueueTest_Comparer() { Point[] points = new Point[10]; for (int i = 0; i < 10; i++) { points[i] = new Point(i, 10 - i); } Shuffle.Do(points); MinPriorityQueue <Point> pq = new MinPriorityQueue <Point>(Point.X_ORDER); foreach (var value in points) { pq.Insert(value); } Assert.IsFalse(pq.IsEmpty()); Assert.AreEqual(10, pq.Size()); Point[] expectPoints = new Point[10]; for (int i = 0; i < 10; i++) { expectPoints[i] = new Point(i, 10 - i); } Shuffle.Do(expectPoints); HeapSort.Sort(expectPoints, Point.X_ORDER, SortOrder.ASC); for (int i = 0; i < 10; i++) { var result = pq.Min(); Assert.AreEqual(expectPoints[i].X, result.X); Assert.AreEqual(expectPoints[i].Y, result.Y); result = pq.DelMin(); Assert.AreEqual(expectPoints[i].X, result.X); Assert.AreEqual(expectPoints[i].Y, result.Y); } Assert.IsTrue(pq.IsEmpty()); Assert.AreEqual(0, pq.Size()); }
public KruskalMST(EdgeWeightedGraph G) { mst = new Queue <Edge>(); MinPriorityQueue <Edge> pq = new MinPriorityQueue <Edge>(); foreach (Edge e in G.edges()) { pq.insert(e); } UF uf = new UF(G.v()); while (!pq.isEmpty() && mst.size() < G.v() - 1) { Edge e = pq.delMin(); int v = e.either(), w = e.other(v); if (uf.connected(v, w)) { continue; } uf.union(v, w); mst.enqueue(e); } }
public void MinPriorityQueueTest_Enumerator() { int[] a = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; Shuffle.Do(a); MinPriorityQueue <int> pq = new MinPriorityQueue <int>(); foreach (var value in a) { pq.Insert(value); } Assert.IsFalse(pq.IsEmpty()); Assert.AreEqual(10, pq.Size()); int expectedValue = 0; foreach (var value in pq) { Assert.AreEqual(expectedValue++, value); } Assert.IsFalse(pq.IsEmpty()); Assert.AreEqual(10, pq.Size()); }
public void MinPriorityQueueDequeueReturnsItemWithLowestPriority() { var priorityQueue = new MinPriorityQueue <string, int>(50); List <Tuple <string, int> > items = new List <Tuple <string, int> > { new Tuple <string, int>("A_50", 50), new Tuple <string, int>("A_41", 41), new Tuple <string, int>("A_38", 38), new Tuple <string, int>("A_37", 37), new Tuple <string, int>("A_23", 23), new Tuple <string, int>("A_11", 11), new Tuple <string, int>("A_5", 5), new Tuple <string, int>("A_3", 3), }.Randomize() .ToList(); priorityQueue.EnqueueRange(items); string item = priorityQueue.Dequeue(); Assert.AreEqual("A_3", item); }
public bool DoTest() { Random random = new Random(Guid.NewGuid().GetHashCode()); List <int> nums = new List <int>(); for (int i = 0; i < INIT_NUM; i++) { nums.Add(random.Next(NUM_RANGE)); } MinPriorityQueue <int> testPq = new MinPriorityQueue <int>(nums.GetEnumerator()); for (int i = 0; i < INSERT_NUM; i++) { testPq.Insert(random.Next(NUM_RANGE)); } List <int> orginNums = new List <int>(); List <int> sortedNums = new List <int>(); while (!testPq.IsEmpty()) { int top = testPq.DelTop(); orginNums.Add(top); sortedNums.Add(top); } sortedNums.Sort(); for (int i = 0; i < orginNums.Count; i++) { if (orginNums[i] != sortedNums[i]) { return(false); } } return(true); }
/// <summary> /// 根据加权无向图,创建最小生成树对象 /// </summary> /// <param name="g"></param> public KruskalMST(EdgeWeightedGraph g) { // 图中所有的顶点 int count = g.countV(); // 初始化 mst this.mst = new QueueList <Edge>(); // 初始化 uf this.uf = new UnionFindTreeWeighted(count); // 初始化 pq this.pq = new MinPriorityQueue <Edge>(g.countE()); // 把图中所有的边存储到pq中 IEnumerator ie = g.edges().GetEnumerator(); while (ie.MoveNext()) { Edge e = (Edge)ie.Current; this.pq.insert(e); } // 遍历pq队列拿到最小权重的边,进行处理 while (!this.pq.isEmpty() && this.mst.length() < g.countV() - 1) { // 找到权重最小边 Edge e = this.pq.delMin(); // 找到该边的两个顶点 int v = e.either(); int w = e.other(v); // 判断这两个顶点是否已经在同一个树中, 如果在同一个树中,则不处理,如果不在同一个树中则合并这两个顶点的树 if (this.uf.connected(v, w)) { continue; } this.uf.union(v, w); // 让e进入到mst中 this.mst.enqueue(e); } }
/************************************************************************************************************/ /// <summary> /// The Dijkstra's algorithm. /// </summary> private void _dijkstra(TGraph graph, TVertex source) { var minPQ = new MinPriorityQueue <TVertex, long>((uint)_verticesCount); int srcIndex = _nodesToIndices[source]; _distances[srcIndex] = 0; // Add all vertices to the queue foreach (var vertex in _nodesToIndices) { minPQ.Enqueue(vertex.Key, _distances[vertex.Value]); } // Main loop while (!minPQ.IsEmpty) { var current = minPQ.DequeueMin(); // get vertex with min weight var currentIndex = _nodesToIndices[current]; // get its index var edges = graph.OutgoingEdges(current); // get its outgoing weighted edges foreach (var edge in edges) { var adjacentIndex = _nodesToIndices[edge.Destination]; var delta = _distances[currentIndex] + edge.Weight; // calculate a new possible weighted path if (delta < _distances[adjacentIndex]) // if true, a shorter path is found from current to adjacent { _edgeTo[adjacentIndex] = edge; _distances[adjacentIndex] = delta; _predecessors[adjacentIndex] = currentIndex; minPQ.UpdatePriority(edge.Destination, delta); // decrease priority with a new edge weight } }//end-foreach }//end-while }
public KruskalMinimumSpanTree(EdgeWeightedGraph g) { mst = new List <Edge>(); var pq = new MinPriorityQueue <Edge>(g.Ecount); foreach (var e in g.Edges()) { pq.Insert(e); } var uf = new UF(g.Vcount); while (!pq.IsEmpty() && mst.Count < g.Vcount - 1) { var e = pq.DelMin(); int v = e.Either; int w = e.Other(v); if (uf.Connected(v, w)) { continue; } uf.Union(v, w); mst.Add(e); } }
public void MinPriorityQueueTest() { var pq = new MinPriorityQueue <string>(9); var results = new List <string>(); pq.Insert("P"); pq.Insert("Q"); pq.Insert("E"); results.Add(pq.DeleteMin()); pq.Insert("X"); pq.Insert("A"); pq.Insert("M"); results.Add(pq.DeleteMin()); pq.Insert("P"); pq.Insert("L"); pq.Insert("E"); results.Add(pq.DeleteMin()); }
private static void Main() { var maxPriorityQueue = new MaxPriorityQueue <string>(); maxPriorityQueue.Enqueue("Buy bread", 15); maxPriorityQueue.Enqueue("Buy milk", 10); maxPriorityQueue.Enqueue("Buy chocolate", 17); maxPriorityQueue.Enqueue("Go to shop", 30); maxPriorityQueue.Enqueue("Go home", 9); Console.WriteLine("Max priority queue: "); maxPriorityQueue.PrintQueue(); var minPriorityQueue = new MinPriorityQueue <string>(); minPriorityQueue.Enqueue("Buy bread", 15); minPriorityQueue.Enqueue("Buy milk", 10); minPriorityQueue.Enqueue("Buy chocolate", 17); minPriorityQueue.Enqueue("Go to shop", 30); minPriorityQueue.Enqueue("Go home", 9); Console.WriteLine("Min priority queue: "); minPriorityQueue.PrintQueue(); }
// run away to the node that's farthest away from all enemies. private KeyValuePair<Result, UnitAction> RunAway() { MinPriorityQueue<UnitAction> farthestActions = new MinPriorityQueue<UnitAction>(); foreach (Node n in pathManager.getAccessibleNodes(subjectRef)) { int curCount = 0; foreach (Unit en in subjectsEnemiesRef) curCount += Node.range(n, en.getNode()); // min priority queue: negate results. UnitAction runAwayTo = new UnitAction(subjectRef, null, n); farthestActions.Enqueue(runAwayTo, -curCount); } if (farthestActions.Count == 0) return new KeyValuePair<Result, UnitAction>(Result.NothingFound, UnitAction.DoNothing(subjectRef)); else return new KeyValuePair<Result, UnitAction>(Result.Success, farthestActions.Dequeue()); }
public void Dequeue_Should_Throw_When_Queue_Is_Empty() { var pq = new MinPriorityQueue <int>(); pq.Invoking(q => q.Dequeue()).Should().Throw <InvalidOperationException>(); }
public OpenSet(int Capacity) { openSet = new MinPriorityQueue <double, Node>(Capacity); }
/// <summary> /// Builds the leaves of the Huffman tree /// </summary> /// <param name="longArray"></param> /// <returns></returns> private MinPriorityQueue<long, BinaryTreeNode<byte>> BuildHuffmanTreeLeaves(long[] ByteArray) { // Build a new Priority Queue MinPriorityQueue<long, BinaryTreeNode<byte>> q = new MinPriorityQueue<long, BinaryTreeNode<byte>>(); for(int x = 0 ;x < ByteArray.Length;x++) { // Check if non-zero if(ByteArray[x] != 0) { // Build new Tree Node with the indicated byte and add to the Byte Array BinaryTreeNode<byte> newNode = new BinaryTreeNode<byte>((byte)x,null, null); q.Add(newNode, ByteArray[x]); } } return q; }
/// <summary> /// Runs MinMax on a unit. /// </summary> /// <returns>A result-UnitAction pair.</returns> private KeyValuePair<Result, UnitAction> MinMax() { List<Node.NodePointer> targets = pathManager.getCurrentTargets(subjectRef); MinPriorityQueue<UnitAction> bestMoves = new MinPriorityQueue<UnitAction>(); int realclay = subjectRef.getClay(); // The "max-y" part: maximize (damage/counter-damage) foreach (Node.NodePointer candidateAttackTarget in targets) { int moveCost = candidateAttackTarget.getDist(); Unit curEnemy = candidateAttackTarget.getTarget().Occupier; AttackRound util = new AttackRound(subjectRef, moveCost, curEnemy); UnitAction roundMove = new UnitAction(subjectRef, curEnemy, candidateAttackTarget.getStart()); int totDmg = 0; // Will very likely die, enqueue this move as bad, and don't move to next step. //TODO: utility = 0 if (util.attackerDies() || util.getUtility() == 0) { bestMoves.Enqueue(roundMove, double.PositiveInfinity); util.resetBack(); subjectRef.setClay(realclay); continue; } totDmg += util.getExpectedDamage(); // Loop through all things that could attack this position, and continue testing attacks. // The "min-y" part. Enemy tries to maximize their (damage/counter-damage) // Technically could just do damage maximization, since counter-damage is fixed. foreach (Unit enemy in subjectsEnemiesRef) { if (enemy.getClay() > 0 && pathManager.canAttack(enemy, candidateAttackTarget.getStart())) { //gets the closest move. This will be the move that maxes damage. int enemyMoveCost = pathManager.maxDamageMoveCost(enemy, candidateAttackTarget.getStart()); AttackRound subRound = new AttackRound(enemy, enemyMoveCost, subjectRef); int roundClay = subjectRef.getClay(); subRound.resetBack(); subjectRef.setClay(roundClay); // If we die, break early, as usual. if (util.defenderDies()) { break; } totDmg += subRound.getExpectedCounterDamage(); } } // Died. Enqueue with +inf again. if (subjectRef.getClay() == 0) bestMoves.Enqueue(roundMove, double.PositiveInfinity); // enqueue move! min pri queue, so invert answer. else bestMoves.Enqueue(roundMove, -((double)totDmg / subjectRef.getClay())); util.resetBack(); subjectRef.setClay(realclay); } subjectRef.setClay(realclay); // no local targets... if (bestMoves.Count == 0) return new KeyValuePair<Result, UnitAction>(Result.NothingFound, null); // all moves die. only move is not to play. else if (bestMoves.currentInversePriority(bestMoves.Peek()) == double.PositiveInfinity) return new KeyValuePair<Result, UnitAction>(Result.WillDie, bestMoves.Peek()); // found good target. return new KeyValuePair<Result, UnitAction>(Result.Success, bestMoves.Peek()); }
/// <summary> /// Returns a sorted list of nodes within a given endurance value. /// Performs a Dijkstra-like algorithm. /// </summary> /// <param name="satifies">The predicate each node must follow.</param> /// <param name="endurance">The maximum endurance to follow out.</param> /// <returns>A sorted list of nodes within a given endurance value.</returns> public List<Node> nodesThatSatisfyPred(Node startNode, System.Predicate<Node> satifies, float endurance = 16.0f, bool stopOnFirst = false, bool isPathfinding = true) { List<Node> foundNodes = new List<Node>(); MinPriorityQueue<Node> nodeList = new MinPriorityQueue<Node>(); initializePathfinding(isPathfinding); startNode.realCost = 0; nodeList.Enqueue(startNode, startNode.realCost); #if DEBUG_PATHFINDER_LOGDEBUG StringBuilder encountered = new StringBuilder(); StringBuilder nodes = new StringBuilder(); nodes.Append("Start node ").Append(startNode.Number).AppendLine(); encountered.Append("Start node ").Append(startNode.Number).AppendLine(); encountered.Append("endurance = ").Append(endurance).AppendLine(); #endif while (nodeList.Count > 0) { //Pick the best looking node, by f-value. Node best = nodeList.Dequeue(); double bestDist = best.realCost; #if DEBUG_PATHFINDER_LOGDEBUG encountered.Append("Node ").Append(best.Number).Append(" ").Append(best).AppendLine(); nodes.Append("Node ").Append(best.Number).AppendLine(); #endif best.Visited = true; if (satifies(best)) { foundNodes.Add(best); if (stopOnFirst) return foundNodes; } //string updateString = "updating: "; foreach (Edge e in best.getEdges()) { Node other = e.getNode(); //We already visited this node, move along, if (other.Visited) continue; //Tentative distance. double testDist = e.getWeight() + bestDist; if (testDist > endurance) continue; //If the other node isn't in the priority queue, add it. if (!nodeList.Contains(other)) { other.CameFrom = best; other.realCost = testDist; nodeList.Enqueue(other, other.realCost); #if DEBUG_PATHFINDER_LOGDEBUG encountered.Append(" added ").Append(other.Number) .Append(", total estimated cost ") .Append(other.realCost).AppendLine(); #endif continue; } //If the other node was a bad path, and this one's better, replace it. else if (other.realCost > testDist) { other.CameFrom = best; other.realCost = testDist; nodeList.Update(other, other.realCost); #if DEBUG_PATHFINDER_LOGDEBUG encountered.Append(" updated ").Append(other.Number) .Append(", total new estimated cost ") .Append(other.realCost).AppendLine(); #endif } } } #if DEBUG_PATHFINDER_LOGDEBUG Debug.Log(encountered); Debug.Log(nodes); #endif return foundNodes; }
// GET: /<controller>/ public IActionResult Index() { string result = string.Empty; // KEYED PRIORITY QUEUE PriorityQueue <int, int, int> keyedPriorityQueue = new PriorityQueue <int, int, int>(10); for (int i = 0; i < 20; ++i) { keyedPriorityQueue.Enqueue(i, i, (i / 3) + 1); } result = result + "Enqueue Keys: "; foreach (var key in keyedPriorityQueue.Keys) { result = result + key + ","; } var keyedPQHighest = keyedPriorityQueue.Dequeue(); result = result + "\nAfter Dequeue, Keyed PQ Highest = " + keyedPQHighest + "\n\n"; // Integer-index priority-queue string alphabet = "abcdefghijklmnopqrstuvwxyz"; result = result + "Alphabets: " + "abcdefghijklmnopqrstuvwxyz" + "\n"; MinPriorityQueue <string, int> priorityQueue = new MinPriorityQueue <string, int>((uint)alphabet.Length); for (int i = 0; i < alphabet.Length; ++i) { priorityQueue.Enqueue(alphabet[i].ToString(), (i / 3) + 1); } var PQMin = priorityQueue.DequeueMin(); result = result + "PQ Min = " + PQMin + "\n\n"; // Processes with priorities MinPriorityQueue <Process, int> sysProcesses = new MinPriorityQueue <Process, int>(); var process1 = new Process( id: 432654, action: new Action(() => System.Console.Write("I am Process #1.\r\n1 + 1 = " + (1 + 1))), desc: "Process 1"); result = result + "Id: " + process1.Id + "\nI am Process #1: 1 + 1 = " + (1 + 1) + "\n\n"; var process2 = new Process( id: 123456, action: new Action(() => System.Console.Write("Hello, World! I am Process #2")), desc: "Process 2"); result = result + "Id: " + process2.Id + "\nHello, World! I am Process #2" + "\n\n"; var process3 = new Process( id: 345098, action: new Action(() => System.Console.Write("I am Process #3")), desc: "Process 3"); result = result + "Id: " + process3.Id + "\nI am Process #3" + "\n\n"; var process4 = new Process( id: 109875, action: new Action(() => System.Console.Write("I am Process #4")), desc: "Process 4"); result = result + "Id: " + process4.Id + "\nI am Process #4" + "\n\n"; var process5 = new Process( id: 13579, action: new Action(() => System.Console.Write("I am Process #5")), desc: "Process 5"); result = result + "Id: " + process5.Id + "\nI am Process #5" + "\n\n"; var process6 = new Process( id: 24680, action: new Action(() => System.Console.Write("I am Process #6")), desc: "Process 6"); result = result + "Id: " + process6.Id + "\nI am Process #6" + "\n\n"; sysProcesses.Enqueue(process1, 1); sysProcesses.Enqueue(process2, 10); sysProcesses.Enqueue(process3, 5); sysProcesses.Enqueue(process4, 7); sysProcesses.Enqueue(process5, 3); sysProcesses.Enqueue(process6, 6); var leastPriorityProcess = sysProcesses.PeekAtMinPriority(); result = result + "First, Least Priority Process.Id = " + leastPriorityProcess.Id + "\n"; sysProcesses.DequeueMin(); leastPriorityProcess = sysProcesses.PeekAtMinPriority(); result = result + "After the second DequeueMin(), Least Priority Process.Id = " + leastPriorityProcess.Id + "\n"; sysProcesses.DequeueMin(); leastPriorityProcess = sysProcesses.PeekAtMinPriority(); result = result + "After the third DequeueMin(), Least Priority Process.Id = " + leastPriorityProcess.Id + "\n"; sysProcesses.DequeueMin(); leastPriorityProcess = sysProcesses.PeekAtMinPriority(); result = result + "After the forth DequeueMin(), Least Priority Process.Id = " + leastPriorityProcess.Id + "\n"; leastPriorityProcess.Action(); HtmlString html = StringHelper.GetHtmlString(result); return(View(html)); }
public void TestFMergeOneNodeAndEmpty() { LeftistTree <KeyValuePair <int, string> > t = new LeftistTree <KeyValuePair <int, string> >(new KeyValuePair <int, string>(2, "two"), null, null); Assert.That(MinPriorityQueue <int, string> .Merge(t, null), Is.EqualTo(t)); }
/// <summary> /// A* on the graph. /// </summary> /// <param name="pathStoreLoc">The Queue to store the path in.</param> /// <param name="start">The starting node.</param> /// <param name="end">The ending node.</param> public double AStar(Queue<Node> pathStoreLoc, Node start, Node end, Node toIgnore = null) { MinPriorityQueue<Node> nodeList = new MinPriorityQueue<Node>(); initializePathfinding(true); if (toIgnore != null) toIgnore.Visited = false; System.Func<Node, Node, float> Heuristic; if (allowedPaths == Paths.quadDir) Heuristic = ManhattenHeuristic; else if (allowedPaths == Paths.octDir) Heuristic = DiagonalHeuristic; else Heuristic = DiagonalHeuristic; start.CameFrom = null; start.heuristicCost = Heuristic(start, end); start.realCost = 0; nodeList.Enqueue(start, start.heuristicCost); #if DEBUG_PATHFINDER_LOGDEBUG StringBuilder encountered = new StringBuilder(); StringBuilder nodes = new StringBuilder(); nodes.Append("Start node ").Append(start.Number).AppendLine(); encountered.Append("Start node ").Append(start.Number).AppendLine(); nodes.Append("End node ").Append(end.Number).AppendLine(); encountered.Append("End node ").Append(end.Number).AppendLine(); #endif while (nodeList.Count > 0) { //Pick the best looking node, by f-value. Node best = nodeList.Dequeue(); double bestDist = best.realCost; #if DEBUG_PATHFINDER_LOGDEBUG encountered.Append("Node ").Append(best.Number).Append(" ").Append(best).AppendLine(); nodes.Append("Node ").Append(best.Number).AppendLine(); #endif //If this is the end, stop, show the path, and return it. if (best.Equals(end)) { ReconstructPath(pathStoreLoc, end); ShowPath(pathStoreLoc); #if DEBUG_PATHFINDER_LOGDEBUG encountered.Append("Finished!\n\nFinal dist: ") .Append(best.realCost).AppendLine(); Debug.Log(encountered); Debug.Log(nodes); #endif return best.realCost; } best.Visited = true; //string updateString = "updating: "; foreach (Edge e in best.getEdges()) { Node other = e.getNode(); //We already visited this node, move along, if (other.Visited) continue; //Tentative distance. double testDist = e.getWeight() + bestDist; //If the other node isn't in the priority queue, add it. if (!nodeList.Contains(other)) { other.CameFrom = best; other.realCost = testDist; other.heuristicCost = Heuristic(other, end); nodeList.Enqueue(other, other.realCost + other.heuristicCost); #if DEBUG_PATHFINDER_LOGDEBUG encountered.Append(" added ").Append(other.Number) .Append(", total estimated cost ") .Append(other.realCost + other.heuristicCost) .AppendLine(); #endif continue; } //If the other node was a bad path, and this one's better, replace it. else if (other.realCost > testDist) { other.CameFrom = best; other.realCost = testDist; nodeList.Update(other, other.realCost + other.heuristicCost); #if DEBUG_PATHFINDER_LOGDEBUG encountered.Append(" updated ").Append(other.Number) .Append(", total new estimated cost ") .Append(other.realCost + other.heuristicCost) .AppendLine(); #endif } } } #if DEBUG_PATHFINDER_LOGDEBUG encountered.Append("Failed!\n"); Debug.Log(encountered); Debug.Log(nodes); #endif return double.PositiveInfinity; }
protected virtual Stack<PathNode> AStar(Tile source, Tile destination) { List<Tile> closed = new List<Tile>(); List<Tile> toDetermine; List<Tile> toAdd = new List<Tile>(); Stack<PathNode> finalPath = null; MinPriorityQueue<PathNode> open = new MinPriorityQueue<PathNode>(); List<PathNode> openList = new List<PathNode>(); open.Enqueue(new PathNode(source, destination)); openList.Add(open.Peek()); PathNode currentNode = null; bool endReached = false; do { currentNode = open.Dequeue(); openList.Remove(currentNode); if (currentNode.HCost == 0) { endReached = true; finalPath = currentNode.GetPath(); } else { closed.Add(tiles[currentNode.Current.X, currentNode.Current.Y]); toDetermine = getAdjacent(currentNode); foreach (Tile t in toDetermine) { bool remove = false; if (t.Collision > source.Unit.Collision) remove = true; if (t.HasUnit()) if (t.Unit.Army != source.Unit.Army) //added so that AI works remove = true; if (closed.Contains(t)) remove = true; //Add this if I want to have no duplicate pathnodes (currently, //multiple exist with different source nodes /* PathNode temp = new PathNode(t.GridwiseLocation, currentNode, destination.GridwiseLocation); foreach (PathNode p in openList) { if (p.Current == temp.Current) { if (p.GCost > temp.GCost) { p.Source = temp.Source; remove = true; } } }'*/ if (!remove) toAdd.Add(t); } foreach (Tile t in toAdd) { PathNode temp = new PathNode(t.GridwiseLocation, currentNode, destination.GridwiseLocation); open.Enqueue(temp); } toAdd.Clear(); } } while (!endReached); return finalPath; }