Priority queue: Difference between revisions
m
Priority Qutue page fix highlighting...
No edit summary |
GordonBGood (talk | contribs) m (Priority Qutue page fix highlighting...) |
||
Line 33:
{{trans|Python}}
<
minheap:heapify(&items)
L !items.empty
print(minheap:pop(&items))</
{{out}}
Line 49:
=={{header|AArch64 Assembly}}==
{{works with|as|Raspberry Pi 3B version Buster 64 bits}}
<
/* ARM assembly AARCH64 Raspberry PI 3B */
/* program priorQueue64.s */
Line 421:
/* for this file see task include a file in language AArch64 assembly */
.include "../includeARM64.inc"
</syntaxhighlight>
{{Output}}
<pre>
Line 436:
The user must type in the monitor the following command after compilation and before running the program!<pre>SET EndProg=*</pre>
{{libheader|Action! Tool Kit}}
<
INCLUDE "D2:ALLOCATE.ACT" ;from the Action! Tool Kit. You must type 'SET EndProg=*' from the monitor after compiling, but before running this program!
Line 541:
TestPop()
TestIsEmpty()
RETURN</
{{out}}
[https://gitlab.com/amarok8bit/action-rosetta-code/-/raw/master/images/Priority_queue.png Screenshot from Atari 8-bit computer]
Line 564:
Ada 2012 includes container classes for priority queues.
<
with Ada.Containers.Unbounded_Priority_Queues;
with Ada.Strings.Unbounded;
Line 605:
end loop;
end;
end Priority_Queues;</
{{out}}
Line 612:
=={{header|ARM Assembly}}==
{{works with|as|Raspberry Pi}}
<
/* ARM assembly Raspberry PI */
/* program priorqueue.s */
Line 1,037:
pop {r2-r4}
bx lr @ return
</syntaxhighlight>
{{out}}
<pre>
Line 1,050:
=={{header|AutoHotkey}}==
<
PQ_TopItem(Queue,Task:=""){ ; remove and return top priority item
TopPriority := PQ_TopPriority(Queue)
Line 1,109:
TopPriority := TopPriority?TopPriority:P , TopPriority := TopPriority<P?TopPriority:P
return, TopPriority
}</
Examples:<
(
3 Clear drains
Line 1,131:
MsgBox, 262208,, % (Task:="Feed cat") " priority = " PQ_Check(PQ,task)"`n`n" PQ_View(PQ)
^Esc::
ExitApp</
=={{header|Axiom}}==
Axiom already has a heap domain for ordered sets.
We define a domain for ordered key-entry pairs and then define a priority queue using the heap domain over the pairs:
<
OrderedKeyEntry(Key:OrderedSet,Entry:SetCategory): Exports == Implementation where
Exports == OrderedSet with
Line 1,162:
setelt(x:%,key:Key,entry:Entry) ==
insert!(construct(key,entry)$S,x)
entry</
pq(3):="Clear drains";
pq(4):="Feed cat";
Line 1,168:
pq(1):="Solve RC tasks";
pq(2):="Tax return";
[extract!(pq) for i in 1..#pq]</
{{out}}
<pre>
Line 1,177:
=={{header|Batch File}}==
Batch has only a data structure, the environment that incidentally sorts itself automatically by key. The environment has a limit of 64K
<
@echo off
setlocal enabledelayedexpansion
Line 1,206:
:next
set order= %order:~-3%
goto:eof</
{{out}}
<pre>
Line 1,218:
=={{header|C}}==
Using a dynamic array as a binary heap. Stores integer priority and a character pointer. Supports push and pop.
<
#include <stdlib.h>
Line 1,289:
return 0;
}
</syntaxhighlight>
{{output}}
<pre>Solve RC tasks
Line 1,298:
=== Pairing heap w/ generic data types ===
header file:
<syntaxhighlight lang=C>
typedef struct _pq_node_t {
long int key;
Line 1,317:
NEW_PQ_ELE(p, k); \
*(h) = heap_merge(((pq_node_t *) (p)), *(h))
</syntaxhighlight>
implementation:
<syntaxhighlight lang=C>
#include <stdlib.h>
#include "pairheap.h"
Line 1,360:
return two_pass_merge(h->down);
}
</syntaxhighlight>
usage:
<syntaxhighlight lang=C>
#include <stdio.h>
#include <string.h>
Line 1,399:
}
}
</syntaxhighlight>
{{Out}}
<pre>
Line 1,412:
===.NET 6 solution===
<
using System.Collections.Generic;
Line 1,444:
5 Make tea
*/</
===Pre-.NET 6 solution===
<
namespace PriorityQueue
Line 1,506:
}
}
}</
'''Min Heap Priority Queue'''
Line 1,512:
{{works with|C sharp|C#|3.0+/DotNet 3.5+}}
The above code is not really a true Priority Queue as it does not allow duplicate keys; also, the SortedList on which it is based does not have O(log n) insertions and removals for random data as a true Priority Queue does. The below code implements a true Min Heap Priority Queue:
<
using KeyT = UInt32;
using System;
Line 1,632:
return toSeq(fromSeq(sq)); }
}
}</
The above class code offers a full set of static methods and properties:
Line 1,654:
The above code can be tested as per the page specification by the following code:
<
Tuple<uint, string>[] ins = { new Tuple<uint,string>(3u, "Clear drains"),
new Tuple<uint,string>(4u, "Feed cat"),
Line 1,676:
foreach (var e in MinHeapPQ<string>.toSeq(MinHeapPQ<string>.adjust((k, v) => new Tuple<uint,string>(6u - k, v), npq)))
Console.WriteLine(e); Console.WriteLine();
}</
It tests building the queue the slow way using repeated "push"'s - O(n log n), the faster "fromSeq" (included in the "sort") - O(n), and also tests the "merge" and "adjust" methods.
Line 1,714:
The C++ standard library contains the <code>std::priority_queue</code> opaque data structure. It implements a max-heap.
<
#include <string>
#include <queue>
Line 1,733:
return 0;
}</
{{out}}
Line 1,747:
and use the heap operations to manipulate it:
<
#include <string>
#include <vector>
Line 1,776:
return 0;
}</
{{out}}
Line 1,789:
=={{header|Clojure}}==
<
; priority-map can be used as a priority queue
Line 1,807:
; Merge priority-maps together
user=> (into p [["Wax Car" 4]["Paint Fence" 1]["Sand Floor" 3]])
{"Solve RC tasks" 1, "Paint Fence" 1, "Clear drains" 3, "Sand Floor" 3, "Wax Car" 4, "Feed cat" 4, "Make tea" 5}</
=={{header|CLU}}==
Line 1,817:
must support the less-than operator.
<
where P has lt: proctype (P,P) returns (bool)
Line 1,911:
stream$putl(po, int$unparse(prio) || ": " || task)
end
end start_up</
{{out}}
<pre>1: Solve RC tasks
Line 1,920:
=={{header|CoffeeScript}}==
<
PriorityQueue = ->
# Use closure style for object creation (so no "new" required).
Line 1,999:
v = new_v
console.log "Final random element was #{v}"
</syntaxhighlight>
output
Line 2,012:
First random element was 0.00002744467929005623
Final random element was 0.9999718656763434
</syntaxhighlight>
=={{header|Common Lisp}}==
In this task were implemented to versions of the functions, the non-destructive ones that will not change the state of the priority queue and the destructive ones that will change. The destructive ones work very similarly to the 'pop' and 'push' functions.
<
;priority-queue's are implemented with association lists
(defun make-pq (alist)
Line 2,049:
(format t "~a~&" (remove-pq a))
(format t "~a~&" a)
</syntaxhighlight>
{{out}}
<pre>
Line 2,062:
=={{header|Component Pascal}}==
BlackBox Component Builder
<
MODULE PQueues;
IMPORT StdLog,Boxes;
Line 2,151:
END PQueues.
</syntaxhighlight>
Interface extracted from the implementation
<
DEFINITION PQueues;
Line 2,176:
END PQueues.
</syntaxhighlight>
Execute: ^Q PQueues.Test<br/>
Output:
Line 2,188:
=={{header|D}}==
<
void main() {
Line 2,202:
heap.removeFront();
}
}</
{{out}}
<pre>Tuple!(int,string)(5, "Make tea")
Line 2,213:
{{libheader| Boost.Generics.Collection}}
Boost.Generics.Collection is part of [https://github.com/MaiconSoft/DelphiBoostLib DelphiBoostLib]
<
{$APPTYPE CONSOLE}
Line 2,230:
with Queue.DequeueEx do
Writeln(Priority, ', ', value);
end.</
{{out}}
<pre>1, Solve RC tasks
Line 2,240:
=={{header|EchoLisp}}==
We use the built-in binary tree library. Each tree node has a datum (key . value). The functions (bin-tree-pop-first tree) and (bin-tree-pop-last tree) allow to extract the node with highest or lowest priority.
<
(lib 'tree)
(define tasks (make-bin-tree 3 "Clear drains"))
Line 2,259:
(bin-tree-pop-last tasks) → (4 . "Feed 🐡")
; etc.
</syntaxhighlight>
=={{header|Elixir}}==
{{trans|Erlang}}
<
def create, do: :gb_trees.empty
Line 2,292:
end
Priority.task</
{{out}}
Line 2,306:
=={{header|Erlang}}==
Using built in gb_trees module, with the suggested interface for this task.
<
-module( priority_queue ).
Line 2,335:
io:fwrite( "top priority: ~p~n", [Element] ),
New_queue.
</syntaxhighlight>
{{out}}
<pre>
Line 2,355:
The following Binomial Heap Priority Queue code has been adapted [http://cs.hubfs.net/topic/None/56608 from a version by "DeeJay"] updated for changes in F# over the intervening years, and implementing the O(1) "peekMin" mentioned in that post; in addition to the above standard priority queue functions, it also implements the "merge" function for which the Binomial Heap is particularly suited, taking O(log n) time rather than the usual O(n) (or worse) time:
<
module PriorityQ =
Line 2,457:
let sort sq = sq |> fromSeq |> toSeq
let adjust f pq = pq |> toSeq |> Seq.map (fun (k, v) -> f k v) |> fromSeq</
"isEmpty", "empty", and "peekMin" all have O(1) performance, "push" is O(1) amortized performance with O(log n) worst case, and the rest are O(log n) except for "fromSeq" (and thus "sort" and "adjust") which have O(n log n) performance since they use repeated "deleteMin" with one per entry.
Line 2,470:
The following code implementing a Min Heap Priority Queue is adapted from the [http://www.cl.cam.ac.uk/~lp15/MLbook/programs/sample4.sml ML PRIORITY_QUEUE code by Lawrence C. Paulson] including separating the key/value pairs as separate entries in the data structure for better comparison efficiency; it implements an efficient "fromSeq" function using reheapify for which the Min Heap is particularly suited as it has only O(n) instead of O(n log n) computational time complexity, which method is also used for the "adjust" and "merge" functions:
<
module PriorityQ =
Line 2,602:
let toSeq pq = Seq.unfold popMin pq
let sort sq = sq |> fromSeq |> toSeq</
The above code implements a "merge" function so that no internal sequence generation is necessary as generation of sequence iterators is quite inefficient in F# for a combined O(n) computational time complexity but a considerable reduction in the constant factor overhead.
Line 2,613:
As the Min Heap is usually implemented as a [http://opendatastructures.org/versions/edition-0.1e/ods-java/10_1_BinaryHeap_Implicit_Bi.html mutable array binary heap] after a genealogical tree based model invented by [https://en.wikipedia.org/wiki/Michael_Eytzinger Michael Eytzinger] over 400 years ago, the following "ugly imperative" code implements the Min Heap Priority Queue this way; note that the code could be implemented not using "ugly" mutable state variables other than the contents of the array (DotNet List which implements a growable array) but in this case the code would be considerably slower as in not much faster or slower than the functional version since using mutable side effects greatly reduces the number of operations:
<
module PriorityQ =
Line 2,696:
let toSeq pq = Seq.unfold popMin pq
let sort sq = sq |> fromSeq |> toSeq</
The comments for the above code are the same as for the functional version; the main difference is that the imperative code takes about two thirds of the time on average.
All of the above codes can be tested under the F# REPL using the following:
<
(4u, "Feed cat");
(5u, "Make tea");
Line 2,719:
printfn ""
testpq |> MinHeap.adjust (fun k v -> uint32 (MinHeap.size testpq) - k, v)
|> MinHeap.toSeq |> Seq.iter (printfn "%A") // test adjust;;</
to produce the following output:
Line 2,765:
=={{header|Factor}}==
Factor has priority queues implemented in the library: documentation is available at http://docs.factorcode.org/content/article-heaps.html (or by typing "heaps" help interactively in the listener).
<
{ 3 "Clear drains" }
{ 4 "Feed cat" }
Line 2,774:
] [
[ print ] slurp-heap
] bi</
output:
<
Tax return
Clear drains
Feed cat
Make tea</
=={{header|Forth}}==
{{works with|gforth|0.7.3}}
<br>
<
\ Priority queue
Line 2,970:
>r 2 s" Tax return" r> >queue
drain-queue</
{{out}}
Line 2,982:
=={{header|Fortran}}==
<
implicit none
Line 3,083:
! 2 -> Tax return
! 1 -> Solve RC tasks
</syntaxhighlight>
=={{header|FreeBASIC}}==
{{trans|VBA}}
<
Prioridad As Integer
Tarea As String
Line 3,173:
Print t.Prioridad; " "; t.Tarea
Loop
Sleep</
{{out}}
<pre>
Line 3,181:
=={{header|FunL}}==
<
native scala.collection.mutable.PriorityQueue
Line 3,202:
while not q.isEmpty()
println( q.dequeue() )</
{{out}}
Line 3,217:
Go's standard library contains the <code>container/heap</code> package, which which provides operations to operate as a heap any data structure that contains the <code>Push</code>, <code>Pop</code>, <code>Len</code>, <code>Less</code>, and <code>Swap</code> methods.
<
import (
Line 3,259:
fmt.Println(heap.Pop(pq))
}
}</
output:
Line 3,272:
=={{header|Groovy}}==
Groovy can use the built in java PriorityQueue class
<
@Canonical
Line 3,289:
while (!empty) { println remove() }
}</
Output:
Line 3,300:
=={{header|Haskell}}==
One of the best Haskell implementations of priority queues (of which there are many) is [http://hackage.haskell.org/package/pqueue pqueue], which implements a binomial heap.
<
main = print (toList (fromList [(3, "Clear drains"),(4, "Feed cat"),(5, "Make tea"),(1, "Solve RC tasks"), (2, "Tax return")]))</
Although Haskell's standard library does not have a dedicated priority queue structure, one can (for most purposes) use the built-in <code>Data.Set</code> data structure as a priority queue, as long as no two elements compare equal (since Set does not allow duplicate elements). This is the case here since no two tasks should have the same name. The complexity of all basic operations is still O(log n) although that includes the "elemAt 0" function to retrieve the first element of the ordered sequence if that were required; "fromList" takes O(n log n) and "toList" takes O(n) time complexity. Alternatively, a <code>Data.Map.Lazy</code> or <code>Data.Map.Strict</code> can be used in the same way with the same limitations.
<
main = print (S.toList (S.fromList [(3, "Clear drains"),(4, "Feed cat"),(5, "Make tea"),(1, "Solve RC tasks"), (2, "Tax return")]))</
{{out}}
<pre>[(1,"Solve RC tasks"),(2,"Tax return"),(3,"Clear drains"),(4,"Feed cat"),(5,"Make tea")]</pre>
Alternatively, a homemade min heap implementation:
<
deriving (Show, Eq)
Line 3,354:
(5, "Make tea"),
(1, "Solve RC tasks"),
(2, "Tax return")]</
The above code is a Priority Queue but isn't a [https://en.wikipedia.org/wiki/Binary_heap Min Heap based on a Binary Heap] for the following reasons: 1) it does not preserve the standard tree structure of the binary heap and 2) the tree balancing can be completely destroyed by some combinations of "pop" operations. The following code is a true purely functional Min Heap implementation and as well implements the extra optional features of Min Heap's that it can build a new Min Heap from a list in O(n) amortized time rather than the O(n log n) amortized time (for a large number of randomly ordered entries) by simply using repeated "push" operations; as well as the standard "push", "peek", "delete" and "pop" (combines the previous two). As well as the "fromList", "toList", and "sort" functions (the last combines the first two), it also has an "isEmpty" function to test for the empty queue, an "adjust" function that applies a function to every entry in the queue and reheapifies in O(n) amortized time and also the "replaceMin" function which is about twice as fast on the average as combined "delete" followed by "push" operations:
<
| MinHeapLeaf !kv
| MinHeapNode !kv {-# UNPACK #-} !Int !(MinHeap a) !(MinHeap a)
Line 3,480:
sortPQ :: (Ord kv) => [kv] -> [kv]
sortPQ ls = toListPQ $ fromListPQ ls</
If one is willing to forgo the fast O(1) "size" function and to give up strict conformance to the Heap tree structure (where rather than building each new level until each left node is full to that level before increasing level to the right, a new level is built by promoting leaves to branches only containing left leaves until all branches have left leaves before filling any right leaves of that level) although having even better tree balancing and therefore at least as high efficiency, one can use the following code adapted from the [http://www.cl.cam.ac.uk/~lp15/MLbook/programs/sample4.sml ''ML'' PRIORITY_QUEUE code by Lawrence C. Paulson] including separating the key/value pairs as separate entries in the data structure for better comparison efficiency; as noted in the code comments, a "size" function to output the number of elements in the queue (fairly quickly in O((log n)^2)), an "adjust" function to apply a function to all elements and reheapify in O(n) time, and a "merge" function to merge two queues has been added to the ML code:
<
| Br !k v !(PriorityQ k v) !(PriorityQ k v)
deriving (Eq, Ord, Read, Show)
Line 3,586:
sortPQ :: (Ord k) => [(k, v)] -> [(k, v)]
sortPQ ls = toListPQ $ fromListPQ ls</
The above codes compile but do not run with GHC Haskell version 7.8.3 using the LLVM back end with LLVM version 3.4 and full optimization turned on under Windows 32; they were tested under Windows 64 and 32 using the Native Code Generator back end with full optimization. With GHC Haskell version 7.10.1 they compile and run with or without LLVM 3.5.1 for 32-bit Windows (64-bit GHC Haskell under Windows does not run with LLVM for version 7.10.1), with a slight execution speed advantage to using LLVM.
Line 3,595:
The above codes when tested with the following "main" function (with a slight modification for the first test when the combined kv entry is used):
<
(4, "Feed cat"),
(5, "Make tea"),
Line 3,612:
mapM_ print $ toListPQ $ mergePQ testPQ testPQ
putStrLn "" -- test adjust
mapM_ print $ toListPQ $ adjustPQ (\x y -> (x * (-1), y)) testPQ</
has the output as follows:
Line 3,658:
<tt>Closure</tt> is used to allow the queue to order lists based on
their first element. The solution only works in Unicon.
<
import Collections # For Heap (dense priority queue) class
Line 3,671:
while task := pq.get() do write(task[1]," -> ",task[2])
end
</syntaxhighlight>
Output when run:
<pre>
Line 3,685:
Implementation:
<
PRI=: ''
Line 3,707:
QUE=: y}.QUE
r
)</
Efficiency is obtained by batching requests. Size of batch for insert is determined by size of arguments. Size of batch for topN is its right argument.
Line 3,713:
Example:
<
3 4 5 1 2 insert__Q 'clear drains';'feed cat';'make tea';'solve rc task';'tax return'
>topN__Q 1
Line 3,721:
clear drains
tax return
solve rc task</
=={{header|Java}}==
Java has a <code>PriorityQueue</code> class. It requires either the elements implement <code>Comparable</code>, or you give it a custom <code>Comparator</code> to compare the elements.
<
class Task implements Comparable<Task> {
Line 3,756:
System.out.println(pq.remove());
}
}</
{{out}}
<pre>
Line 3,771:
The special key "priorities" is used to store the priorities in a sorted array. Since "sort" is fast we will use that rather than optimizing insertion in the priorities array.
We assume that if an item of a given priority is already in the priority queue, there is no need to add it again.<
# Add an item with the given priority (an integer,
Line 3,820:
def prioritize:
. as $list | {} | pq_add_tasks($list) | pq_pop_tasks ;
</syntaxhighlight>
The specific task:
<syntaxhighlight lang=jq>
[ [3, "Clear drains"],
[4, "Feed cat"],
Line 3,829:
[2, "Tax return"]
] | prioritize
</syntaxhighlight>
{{Out}}
"Solve RC tasks"
Line 3,839:
=={{header|Julia}}==
Julia has built-in support for priority queues, though the <code>PriorityQueue</code> type is not exported by default. Priority queues are a specialization of the <code>Dictionary</code> type having ordered values, which serve as the priority. In addition to all of the methods of standard dictionaries, priority queues support: <code>enqueue!</code>, which adds an item to the queue, <code>dequeue!</code> which removes the lowest priority item from the queue, returning its key, and <code>peek</code>, which returns the (key, priority) of the lowest priority entry in the queue. The ordering behavior of the queue, which by default is its value sort order (typically low to high), can be set by passing an order directive to its constructor. For this task, <code>Base.Order.Reverse</code> is used to set-up the <code>task</code> queue to return tasks from high to low priority.
<
using Base.Collections
Line 3,858:
dequeue!(task)
println(" \"", t, "\" has priority ", p)
end</
{{out}}
Line 3,871:
=={{header|Kotlin}}==
{{trans|Java}}
<
internal data class Task(val priority: Int, val name: String) : Comparable<Task> {
Line 3,890:
"Tax return" priority 2))
while (q.any()) println(q.remove())
}</
{{out}}
<pre>Task(priority=1, name=Solve RC tasks)
Line 3,899:
=={{header|Lasso}}==
<
data
store = map,
Line 3,957:
while(not #test->isEmpty) => {
stdout(#test->pop)
}</
{{out}}
Line 3,966:
This implementation uses a table with priorities as keys and queues as values. Queues for each priority are created when putting items as needed and are shrunk as necessary when popping items and removed when they are empty. Instead of using a plain array table for each queue, the technique shown in the Lua implementation from the [[Queue/Definition#Lua | Queue]] task is used. This avoids having to use <code>table.remove(t, 1)</code> to get and remove the first queue element, which is rather slow for big tables.
<
__index = {
put = function(self, p, v)
Line 4,015:
for prio, task in pq.pop, pq do
print(string.format("Popped: %d - %s", prio, task))
end</
'''Output:'''
Line 4,032:
The implementation is faster than the Python implementations below using <code>queue.PriorityQueue</code> or <code>heapq</code>, even when comparing the standard Lua implementation against [[PyPy]] and millions of tasks are added to the queue. With LuaJIT it is yet faster. The following code measures the time needed to add 10<sup>7</sup> tasks with a random priority between 1 and 1000 and to retrieve them from the queue again in order.
<
-- since it has millisecond precision on most systems
local socket = require("socket")
Line 4,071:
end
print(string.format("Elapsed: %.3f ms.", (socket.gettime() - start) * 1000))</
=={{header|M2000 Interpreter}}==
Line 4,077:
===Using unordered array===
<
Module UnOrderedArray {
Class PriorityQueue {
Line 4,194:
}
UnOrderedArray
</syntaxhighlight>
===Using a stack with arrays as elements===
Every insertion push item using binary search in proper position. Pop is very fast.
<
Module PriorityQueue {
a= ( (3, "Clear drains"), (4 ,"Feed cat"), ( 5 , "Make tea"), ( 1 ,"Solve RC tasks"), ( 2 , "Tax return"))
Line 4,260:
PriorityQueue
</syntaxhighlight>
===Using a stack with Groups as elements===
This is the same as previous but now we use a group (a user object for M2000). InsertPQ is the same as before. Lambda comp has change only. We didn't use pointers to groups. All groups here works as values, so when we get a peek we get a copy of group in top position. All members of a group may not values, so if we have a pointer to group then we get a copy of that pointer, but then we can make changes and that changes happen for the group which we get the copy.
<
Module PriorityQueueForGroups {
class obj {
Line 4,323:
}
PriorityQueueForGroups
</syntaxhighlight>
=={{header|Mathematica}}/{{header|Wolfram Language}}==
<
queue = SortBy[Append[queue, {priority, item}], First], HoldFirst];
pop = Function[queue,
Line 4,335:
If[Length@queue == 0, Null, Max[queue[[All, 1]]]], HoldFirst];
merge = Function[{queue1, queue2},
SortBy[Join[queue1, queue2], First], HoldAll];</
Example:
<
push[queue, 3, "Clear drains"];
push[queue, 4, "Feed cat"];
Line 4,349:
queue1 = {};
push[queue1, 6, "Drink tea"];
Print[merge[queue, queue1]];</
Output:
Line 4,360:
=={{header|Maxima}}==
<
The key may be any number (integer or not). Items are extracted in FIFO order. */
Line 4,441:
"call friends"
"serve cider"
"savour !"</
=={{header|Mercury}}==
Mercury comes with an efficient, albeit simple, priority queue in its standard library. The build_pqueue/2 predicate in the code below inserts the test data in arbitrary order. display_pqueue/3, in turn, removes one K/V pair at a time, displaying the value. Compiling and running the supplied program results in all tasks being displayed in priority order as expected.
<
:- interface.
Line 4,480:
main(!IO) :-
build_pqueue(pqueue.init, PQO),
display_pqueue(PQO, !IO).</
=={{header|Nim}}==
{{trans|C}}
<
PriElem[T] = tuple
data: T
Line 4,543:
while p.count > 0:
echo p.pop()</
{{out}}
<pre>(data: Solve RC tasks, pri: 1)
Line 4,552:
''' Using Nim HeapQueue'''
<
var pq = newHeapQueue[(int, string)]()
Line 4,563:
while pq.len() > 0:
echo pq.pop()</
{{out}}
Line 4,573:
''' Using Nim tables'''
<
var
Line 4,590:
pq.del(i)
main()</
{{out}}
<pre>1: Solve RC tasks
Line 4,602:
The priority queue used in this example is not actually written in Objective-C. It is part of Apple's (C-based) Core Foundation library, which is included with in Cocoa on Mac OS X and iOS. Its interface is a C function interface, which makes the code very ugly. Core Foundation is not included in GNUStep or other Objective-C APIs.
<
const void *PQRetain(CFAllocatorRef allocator, const void *ptr) {
Line 4,665:
}
return 0;
}</
log:
Line 4,680:
Holger Arnold's [http://holgerarnold.net/software/ OCaml base library] provides a [http://holgerarnold.net/software/ocaml/doc/base/PriorityQueue.html PriorityQueue] module.
<
let () =
Line 4,696:
PQ.remove_first pq;
print_endline task
done</
testing:
Line 4,708:
Although OCaml's standard library does not have a dedicated priority queue structure, one can (for most purposes) use the built-in Set data structure as a priority queue, as long as no two elements compare equal (since Set does not allow duplicate elements). This is the case here since no two tasks should have the same name. Note that Set is a functional, persistent data structure, so we derive new priority queues from the old ones functionally, rather than modifying them imperatively; the complexity is still O(log n).
{{works with|OCaml|4.02+}}
<
(struct
type t = int * string (* pair of priority and task name *)
Line 4,729:
aux (PQSet.remove task pq')
end
in aux pq</
{{out}}
<pre>
Line 4,905:
(buffer empty)
*/
</syntaxhighlight>
=={{header|Pascal}}==
<
program PriorityQueueTest;
Line 4,983:
Queue.free;
end.
</syntaxhighlight>
=={{header|Perl}}==
There are a few implementations on CPAN. Following uses <code>Heap::Priority</code>[http://search.cpan.org/~fwojcik/Heap-Priority-0.11/Priority.pm]
<
use strict;
use Heap::Priority;
Line 5,000:
["Tax return", 2];
say while ($_ = $h->pop);</
Feed cat
Clear drains
Tax return
Solve RC tasks</
===IBM card sorter version===
<
use strict; # https://rosettacode.org/wiki/Priority_queue
Line 5,038:
delete $bins[-1] while @bins and @{ $bins[-1] // [] } == 0;
shift @{ $bins[-1] // [] };
}</
{{out}}
<pre>
Line 5,052:
Dictionary based solution. Allows duplicate tasks, FIFO within priority, and uses a callback-style method of performing tasks.<br>
Assumes 5 is the highest priority and should be done first, for 1 first just delete the ",true" on traverse_dict calls.
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">tasklist</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">new_dict</span><span style="color: #0000FF;">()</span>
Line 5,108:
<span style="color: #0000FF;">?</span><span style="color: #008000;">"==="</span>
<span style="color: #000000;">list_tasks</span><span style="color: #0000FF;">()</span>
<!--</
{{out}}
<pre>
Line 5,128:
(I needed this for [[Taxicab_numbers#Phix|Taxicab_numbers]])<br>
The bulk of this code now forms builtins/pqueue.e (not properly documented at the time, but now is, see below)
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #004080;">sequence</span> <span style="color: #000000;">pq</span> <span style="color: #0000FF;">=</span> <span style="color: #0000FF;">{}</span>
Line 5,185:
<span style="color: #0000FF;">?</span><span style="color: #000000;">pqPop</span><span style="color: #0000FF;">()</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<!--</
{{out}}
The optional initial set_rand() makes it slightly more amusing.<br>
Line 5,204:
=== builtin ===
If you omit MAX_HEAP or (same thing) specify MIN_HEAP, the output'll be 1..5
<!--<
<span style="color: #008080;">with</span> <span style="color: #008080;">javascript_semantics</span>
<span style="color: #008080;">constant</span> <span style="color: #000000;">tasklist</span> <span style="color: #0000FF;">=</span> <span style="color: #7060A8;">pq_new</span><span style="color: #0000FF;">(</span><span style="color: #004600;">MAX_HEAP</span><span style="color: #0000FF;">)</span>
Line 5,218:
<span style="color: #7060A8;">printf</span><span style="color: #0000FF;">(</span><span style="color: #000000;">1</span><span style="color: #0000FF;">,</span><span style="color: #008000;">"%d: %s\n"</span><span style="color: #0000FF;">,{</span><span style="color: #000000;">priority</span><span style="color: #0000FF;">,</span><span style="color: #000000;">task</span><span style="color: #0000FF;">})</span>
<span style="color: #008080;">end</span> <span style="color: #008080;">while</span>
<!--</
{{out}}
<pre>
Line 5,229:
=={{header|Phixmonti}}==
<
by Galileo, 05/2022 #/
Line 5,237:
( 3 "Clear drains" ) 0 put ( 4 "Feed cat" ) 0 put ( 5 "Make tea" ) 0 put ( 1 "Solve RC tasks" ) 0 put ( 2 "Tax return" ) 0 put
sort pop swap print pstack
</syntaxhighlight>
{{out}}
<pre>[1, "Solve RC tasks"]
Line 5,247:
{{works with|PHP|5.3+}}
PHP's <code>SplPriorityQueue</code> class implements a max-heap. PHP also separately has <code>SplHeap</code>, <code>SplMinHeap</code>, and <code>SplMaxHeap</code> classes.
<
$pq = new SplPriorityQueue;
Line 5,263:
print_r($pq->extract());
}
?></
Output:
Line 5,296:
{{works with|PHP|5.3+}}
The difference between <code>SplHeap</code> and <code>SplPriorityQueue</code> is that <code>SplPriorityQueue</code> takes the data and the priority as two separate arguments, and the comparison is only made on the priority; whereas <code>SplHeap</code> takes only one argument (the element), and the comparison is made on that directly. In all of these classes it is possible to provide a custom comparator by subclassing the class and overriding its <code>compare</code> method.
<
$pq = new SplMinHeap;
Line 5,308:
print_r($pq->extract());
}
?></
Output:
Line 5,341:
=={{header|Picat}}==
Picat has built-in support for min and max heaps.
<
Tasks = [[3,"Clear drains"],
[4,"Feed cat"],
Line 5,357:
nl,
println("Pop the elements from the queue:"),
println([Heap.heap_pop() : _ in 1..Heap.heap_size]).</
{{out}}
Line 5,373:
The heaps creation functions can take the task list as argument:
<
[4,"Feed cat"],
[5,"Make tea"],
Line 5,379:
[2,"Tax return"]],
Heap = new_min_heap(Tasks),
println([Heap.heap_pop() : _ in 1..Heap.heap_size]).</
=={{header|PicoLisp}}==
The following implementation imposes no limits. It uses a [http://software-lab.de/doc/refI.html#idx binary tree] for storage. The priority levels may be numeric, or of any other type.
<
(de insertPQ (Queue Prio Item)
(idx Queue (cons Prio Item) T) )
Line 5,401:
# Merge second queue into first
(de mergePQ (Queue1 Queue2)
(balance Queue1 (sort (conc (idx Queue1) (idx Queue2)))) )</
Test:
<
(off Pq1 Pq2)
Line 5,420:
# Remove and print all items from first queue
(while Pq1
(println (removePQ 'Pq1)) )</
Output:
<pre>(Solve RC tasks)
Line 5,428:
(Make tea)</pre>
=== Alternative version using a pairing heap: ===
<
(de heap-first (H) (car H))
Line 5,452:
(de heap-rest (H)
("merge-pairs" (cdr H)))
</syntaxhighlight>
Test:
<
(setq H NIL)
(for
Line 5,470:
(bye)
</syntaxhighlight>
{{Out}}
<pre>
Line 5,485:
Example of use :
<
TL0 = [3-'Clear drains',
4-'Feed cat'],
Line 5,513:
heap_to_list(Heap4, TL2),
writeln('Content of the queue'), maplist(writeln, TL2).
</syntaxhighlight>
The output :
<pre>1 ?- priority-queue.
Line 5,537:
The map stores the elements of a given priority in a FIFO list.
Priorities can be any signed 32 value.
<
List description.s() ;implements FIFO queue
EndStructure
Line 5,655:
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
CloseConsole()
EndIf</
{{out}}
<pre>Solve RC tasks
Line 5,675:
The data structures in the "queue" module are synchronized multi-producer, multi-consumer queues for multi-threaded use. They can however handle this task:
<
>>> pq = queue.PriorityQueue()
>>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")):
Line 5,690:
(4, 'Feed cat')
(5, 'Make tea')
>>> </
;Help text for queue.PriorityQueue:
<
>>> help(queue.PriorityQueue)
Help on class PriorityQueue in module queue:
Line 5,799:
| list of weak references to the object (if defined)
>>> </
===Using heapq===
Line 5,805:
Although one can use the heappush method to add items individually to a heap similar to the method used in the PriorityQueue example above, we will instead transform the list of items into a heap in one go then pop them off one at a time as before.
<
>>> items = [(3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")]
>>> heapify(items)
Line 5,817:
(4, 'Feed cat')
(5, 'Make tea')
>>> </
;Help text for module heapq:
<
Help on module heapq:
Line 5,908:
>>> </
Line 5,915:
For more examples uf usage, see [[Sorting algorithms/Heapsort#Quackery]] and [[Huffman coding#Quackery]]
<
[ stack ] is heap.pq ( --> s )
Line 6,012:
swap echo say ": "
echo$ cr ]
drop</
{{out}}
Line 6,025:
=={{header|R}}==
Using closures:
<
keys <- values <- NULL
insert <- function(key, value) {
Line 6,050:
while(!pq$empty()) {
with(pq$pop(), cat(key,":",value,"\n"))
}</
2 : Tax return
3 : Clear drains
4 : Feed cat
5 : Make tea</
setRefClass("PriorityQueue",
fields = list(keys = "numeric", values = "list"),
Line 6,070:
},
empty = function() length(keys) == 0
))</
=={{header|Racket}}==
This solution implements priority queues on top of heaps.
<
#lang racket
(require data/heap)
Line 6,099:
(remove-min!)
(remove-min!)
</syntaxhighlight>
Output:
<
"Solve RC tasks"
"Tax return"
Line 6,107:
"Feed cat"
"Make tea"
</syntaxhighlight>
=={{header|Raku}}==
Line 6,115:
The tasks are stored internally as an array of FIFO buffers, so multiple tasks of the same priority level will be returned in the order they were stored.
<
has @!tasks;
Line 6,142:
}
say $pq.get until $pq.is-empty;</
{{out}}
Line 6,157:
===version 1===
Programming note: this REXX version allows any number (with or without decimals, say, '''5.7''') for the priority, including negative numbers.
<
#=0; @.= /*0 tasks; nullify the priority queue.*/
say '══════ inserting tasks.'; call .ins 3 "Clear drains"
Line 6,178:
if top=='' | _>top then do; top=_; top#=j; end
end /*j*/
return top#</
{{out|output}}
<pre>
Line 6,195:
===version 2===
<
n=0
task.=0 /* for the sake of task.0done.* */
Line 6,236:
task.0done.j=1
todo=todo-1
return res</
{{out}}
<pre>------ inserting tasks.
Line 6,258:
=={{header|Ruby}}==
A naive, inefficient implementation
<
def initialize(data=nil)
@q = Hash.new {|h, k| h[k] = []}
Line 6,339:
puts pq3.pop
end
puts "peek : #{pq3.peek}"</
{{out}}
Line 6,366:
=={{header|Run BASIC}}==
<
#mem execute("CREATE TABLE queue (priority float,descr text)")
Line 6,410:
print priority;" ";descr$
next i
RETURN</
{{out}}
<pre> -------------- Find first priority ---------------------
Line 6,427:
=={{header|Rust}}==
<
use std::cmp::Ordering;
use std::borrow::Cow;
Line 6,474:
println!("{}", item.task);
}
}</
{{out}}
<pre>Solve RC tasks
Line 6,484:
=={{header|SAS}}==
Using macros in a SAS data step:
<
do;
_len = 0;
Line 6,579:
%HeapPop;
end;
run;</
{{output}}
<pre>1 Solve RC tasks
Line 6,588:
An implementation using <code>proc ds2</code> may be more structured:
<
package Heap / overwrite=yes;
dcl int _entryorder _size _len _entryOrders[1000];
Line 6,697:
end;
enddata;
run;</
=={{header|Scala}}==
Scala has a class PriorityQueue in its standard library.
<
case class Task(prio:Int, text:String) extends Ordered[Task] {
def compare(that: Task)=that.prio compare this.prio
Line 6,709:
var q=PriorityQueue[Task]() ++ Seq(Task(3, "Clear drains"), Task(4, "Feed cat"),
Task(5, "Make tea"), Task(1, "Solve RC tasks"), Task(2, "Tax return"))
while(q.nonEmpty) println(q dequeue)</
Output:
<pre>Task(1,Solve RC tasks)
Line 6,717:
Task(5,Make tea)</pre>
Instead of deriving the class from Ordering an implicit conversion could be provided.
<
implicit def taskOrdering=new Ordering[Task] {
def compare(t1:Task, t2:Task):Int=t2.prio compare t1.prio
}</
=={{header|SenseTalk}}==
We use New to create an object instance -- in this case (for simplicity) based on the script itself, which is named PriorityQueue. The Tell command or dot notation are then used to send messages directly to that object.
<
// PriorityQueue.script
set Tasks to a new PriorityQueue
Line 6,765:
return (priority of each && task of each for each item of my queue) joined by return
end report
</syntaxhighlight>
{{out}}
<pre>
Line 6,786:
=={{header|Sidef}}==
{{trans|Raku}}
<
has tasks = []
Line 6,815:
}
say pq.get while !pq.is_empty</
{{out}}
Line 6,833:
Note: this is a max-heap
<
type priority = int
val compare = Int.compare
Line 6,861:
in
aux pq
end</
testing:
Line 6,876:
Using <code>mata</code>, which has 1-based arrays:
<
struct Node {
real scalar time
Line 6,978:
testHeap(0)
end
</syntaxhighlight>
{{out}}
<pre>
Line 7,001:
You can use <code>CFBinaryHeap</code> from Core Foundation, but it is super ugly due to the fact that <code>CFBinaryHeap</code> operates on generic pointers, and you need to convert back and forth between that and objects.
{{works with|Swift|2.x}}
<
var priority : Int
var name: String
Line 7,056:
while pq.count != 0 {
print(pq.pop())
}</
{{out}}
Line 7,069:
=={{header|Tcl}}==
{{tcllib|struct::prioqueue}}
<
set pq [struct::prioqueue]
Line 7,086:
# Remove the front-most item from the priority queue
puts [$pq get]
}</
Which produces this output:
<pre>
Line 7,162:
For b@ = Set(b, b+1) To a@ + 1 Step -1: @(b@) = @(b@-1) : Next
Return
</
{{Out}}
First an entry is dequeued from an empty queue. Then all entries are inserted and listed. Finally, another entry is dequeued and the remainder of the entries is listed again.
Line 7,184:
=={{header|VBA}}==
<
Priority As Integer
Data As String
Line 7,262:
Debug.Print t.Priority, t.Data
Loop
End Sub</
2 Tax return
3 Clear drains
Line 7,271:
=={{header|VBScript}}==
I wrote this priority queue in a class. It uses a dynamic array to implement the class. Function out_of_order must be adapted to the data. Run it with CScript.
<syntaxhighlight lang=vb>
option explicit
Class prio_queue
Line 7,377:
set queue= nothing
</syntaxhighlight>
Output:
<pre>
Line 7,392:
{{libheader|Wren-queue}}
The above module contains a PriorityQueue class. Unlike some other languages here, the higher the number, the higher the priority. So the 'Make tea' task has the highest priority and, thankfully, the cat has a good chance of being fed!
<
var tasks = PriorityQueue.new()
Line 7,403:
var t = tasks.pop()
System.print(t)
}</
{{out}}
Line 7,422:
The <code>'PUSH</code> method never needs to search down the levels. The efficiency bottleneck here is probably the implementation of <code>NCONC</code> (used for adding the new item to the end of the queue at the relevant level). A priority <i>stack</i>, with first in / last out at each priority level rather than first in / first out, would be faster.
<
(instance-variables queue lowest-priority most-urgent) )
Line 7,456:
(define-method (priority-queue 'emptyp)
(and (= most-urgent lowest-priority) (null (vector-ref queue most-urgent))) )</
The example uses strings, but the data items stored in the priority queue can be of any type (including the empty list—or even other priority queues).
<
(pq 'push "Clear drains" 3)
Line 7,465:
(pq 'push "Make tea" 5)
(pq 'push "Solve RC tasks" 1)
(pq 'push "Tax return" 2)</
{{out}}
Items are popped beginning from the most urgent:
<
"Solve RC tasks"
[2] (pq 'pop)
"Tax return"</
Within each priority level, new items are pushed onto the end and popped from the beginning of the list (a queue is a first in / first out data structure):
<
("Feed cat" "Answer emails")</
Attempting to push with an invalid priority value returns the empty list, i.e. false:
<
()</
<code>'EMPTYP</code> returns false if the priority queue is not empty:
<
()</
<code>'PEEK</code> non-destructively returns the item that would be popped if you called <code>'POP</code>:
<
"Clear drains"</
If you want to examine a whole priority queue, the built-in <code>'SHOW</code> method allows you to do so:
<
Object is #<Object:PRIORITY-QUEUE #x4e2cba8>, Class is #<Class:PRIORITY-QUEUE #x4e254c8>
Line 7,498:
LOWEST-PRIORITY = 5
MOST-URGENT = 3
#<Object:PRIORITY-QUEUE #x4e2cba8></
Once all the items have been popped, the priority queue is empty and <code>'EMPTYP</code> then returns true:
<
"Clear drains"
Line 7,514:
[12] (pq 'emptyp)
#T</
Attempting to pop from an empty priority queue returns false:
<
()</
=={{header|Zig}}==
Line 7,526:
Save the following code as <code>priority_queue.zig</code>, and run the tests using <code>zig test priority_queue.zig</code>.
<
const std = @import("std");
const PriorityQueue = std.PriorityQueue;
Line 7,612:
}
</syntaxhighlight>
Sample output:
<
$ zig test priority_queue.zig
Test [1/2] test "priority queue (max heap)"...
Line 7,633:
All 2 tests passed.
</syntaxhighlight>
=={{header|zkl}}==
This solution uses a [hopefully small] fixed number of priorities, each of which has an unordered list of tasks. This allows O(1) insertions, O(p) for retrievals (p is the number of priorities).
<
fcn init(numLevels=10){ // 0..numLevels, bigger # == lower priorty
var [const] queue=(1).pump(numLevels+1,List.createLong(numLevels).write,L().copy);
Line 7,656:
fcn walker{ state.clear().append(0,0); Walker(next) } // iterator front end
fcn toString{ "PQ(%d) items".fmt(queue.reduce(fcn(sum,q){ sum+q.len() },0)) }
}</
<
foreach x in
(T("Clear drains",3, "Feed cat",4, "Make tea",5, "Solve RC tasks",1, "Tax return",2,
Line 7,669:
println("ToDo list:");
foreach item in (pq){ item.println() }
pq.println();</
{{out}}
<pre>
|