tasks a-s
This commit is contained in:
parent
47bf37c096
commit
b83f433714
12433 changed files with 156208 additions and 123 deletions
17
Task/Priority-queue/0DESCRIPTION
Normal file
17
Task/Priority-queue/0DESCRIPTION
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
A [[wp:Priority queue|priority queue]] is somewhat similar to a [[Queue|queue]], with an important distinction: each item is added to a priority queue with a priority level, and will be later removed from the queue with the highest priority element first. That is, the items are (conceptually) stored in the queue in priority order instead of in insertion order.
|
||||
|
||||
'''Task:''' Create a priority queue. The queue must support at least two operations:
|
||||
# Insertion. An element is added to the queue with a priority (a numeric value).
|
||||
# Top item removal. Deletes the element or one of the elements with the current top priority and return it.
|
||||
|
||||
Optionally, other operations may be defined, such as peeking (find what current top priority/top element is), merging (combining two priority queues into one), etc.
|
||||
|
||||
To test your implementation, insert a number of elements into the queue, each with some random priority. Then dequeue them sequentially; now the elements should be sorted by priority. You can use the following task/priority items as input data:
|
||||
'''Priority''' '''Task'''
|
||||
3 Clear drains
|
||||
4 Feed cat
|
||||
5 Make tea
|
||||
1 Solve RC tasks
|
||||
2 Tax return
|
||||
|
||||
The implementation should try to be efficient. A typical implementation has O(log n) insertion and extraction time, where n is the number of items in the queue. You may choose to impose certain limits such as small range of allowed priority levels, limited capacity, etc. If so, discuss the reasons behind it.
|
||||
42
Task/Priority-queue/Ada/priority-queue.ada
Normal file
42
Task/Priority-queue/Ada/priority-queue.ada
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
with Ada.Containers.Synchronized_Queue_Interfaces;
|
||||
with Ada.Containers.Unbounded_Priority_Queues;
|
||||
with Ada.Strings.Unbounded;
|
||||
|
||||
procedure Priority_Queues is
|
||||
use Ada.Containers;
|
||||
use Ada.Strings.Unbounded;
|
||||
type Queue_Element is record
|
||||
Priority : Natural;
|
||||
Content : Unbounded_String;
|
||||
end record;
|
||||
function Get_Priority (Element : Queue_Element) return Natural is
|
||||
begin
|
||||
return Element.Priority;
|
||||
end Get_Priority;
|
||||
function Before (Left, Right : Natural) return Boolean is
|
||||
begin
|
||||
return Left > Right;
|
||||
end Before;
|
||||
package String_Queues is new Synchronized_Queue_Interfaces
|
||||
(Element_Type => Queue_Element);
|
||||
package String_Priority_Queues is new Unbounded_Priority_Queues
|
||||
(Queue_Interfaces => String_Queues,
|
||||
Queue_Priority => Natural);
|
||||
|
||||
My_Queue : String_Priority_Queues.Queue;
|
||||
begin
|
||||
My_Queue.Enqueue (New_Item => (Priority => 3, Content => To_Unbounded_String ("Clear drains")));
|
||||
My_Queue.Enqueue (New_Item => (Priority => 4, Content => To_Unbounded_String ("Feed cat")));
|
||||
My_Queue.Enqueue (New_Item => (Priority => 5, Content => To_Unbounded_String ("Make tea")));
|
||||
My_Queue.Enqueue (New_Item => (Priority => 1, Content => To_Unbounded_String ("Solve RC tasks")));
|
||||
My_Queue.Enqueue (New_Item => (Priority => 2, Content => To_Unbounded_String ("Tax return")));
|
||||
|
||||
declare
|
||||
Element : Queue_Element;
|
||||
begin
|
||||
while My_Queue.Current_Use > 0 loop
|
||||
My_Queue.Dequeue (Element => Element);
|
||||
Ada.Text_IO.Put_Line (Natural'Image (Element.Priority) & " => " & To_String (Element.Content));
|
||||
end loop;
|
||||
end;
|
||||
end Priority_Queues;
|
||||
27
Task/Priority-queue/Axiom/priority-queue-1.axiom
Normal file
27
Task/Priority-queue/Axiom/priority-queue-1.axiom
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
)abbrev Domain ORDKE OrderedKeyEntry
|
||||
OrderedKeyEntry(Key:OrderedSet,Entry:SetCategory): Exports == Implementation where
|
||||
Exports == OrderedSet with
|
||||
construct: (Key,Entry) -> %
|
||||
elt: (%,"key") -> Key
|
||||
elt: (%,"entry") -> Entry
|
||||
Implementation == add
|
||||
Rep := Record(k:Key,e:Entry)
|
||||
x,y: %
|
||||
construct(a,b) == construct(a,b)$Rep @ %
|
||||
elt(x,"key"):Key == (x@Rep).k
|
||||
elt(x,"entry"):Entry == (x@Rep).e
|
||||
x < y == x.key < y.key
|
||||
x = y == x.key = y.key
|
||||
hash x == hash(x.key)
|
||||
if Entry has CoercibleTo OutputForm then
|
||||
coerce(x):OutputForm == bracket [(x.key)::OutputForm,(x.entry)::OutputForm]
|
||||
)abbrev Domain PRIORITY PriorityQueue
|
||||
S ==> OrderedKeyEntry(Key,Entry)
|
||||
PriorityQueue(Key:OrderedSet,Entry:SetCategory): Exports == Implementation where
|
||||
Exports == PriorityQueueAggregate S with
|
||||
heap : List S -> %
|
||||
setelt: (%,Key,Entry) -> Entry
|
||||
Implementation == Heap(S) add
|
||||
setelt(x:%,key:Key,entry:Entry) ==
|
||||
insert!(construct(key,entry)$S,x)
|
||||
entry
|
||||
7
Task/Priority-queue/Axiom/priority-queue-2.axiom
Normal file
7
Task/Priority-queue/Axiom/priority-queue-2.axiom
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
pq := empty()$PriorityQueue(Integer,String)
|
||||
pq(3):="Clear drains";
|
||||
pq(4):="Feed cat";
|
||||
pq(5):="Make tea";
|
||||
pq(1):="Solve RC tasks";
|
||||
pq(2):="Tax return";
|
||||
[extract!(pq) for i in 1..#pq]
|
||||
3
Task/Priority-queue/Axiom/priority-queue-3.axiom
Normal file
3
Task/Priority-queue/Axiom/priority-queue-3.axiom
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
[[5,"Make tea"], [4,"Feed cat"], [3,"Clear drains"], [2,"Tax return"],
|
||||
[1,"Solve RC tasks"]]
|
||||
Type: List(OrderedKeyEntry(Integer,String))
|
||||
20
Task/Priority-queue/C++/priority-queue-1.cpp
Normal file
20
Task/Priority-queue/C++/priority-queue-1.cpp
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
#include <iostream>
|
||||
#include <string>
|
||||
#include <queue>
|
||||
#include <utility>
|
||||
|
||||
int main() {
|
||||
std::priority_queue<std::pair<int, std::string> > pq;
|
||||
pq.push(std::make_pair(3, "Clear drains"));
|
||||
pq.push(std::make_pair(4, "Feed cat"));
|
||||
pq.push(std::make_pair(5, "Make tea"));
|
||||
pq.push(std::make_pair(1, "Solve RC tasks"));
|
||||
pq.push(std::make_pair(2, "Tax return"));
|
||||
|
||||
while (!pq.empty()) {
|
||||
std::cout << pq.top().first << ", " << pq.top().second << std::endl;
|
||||
pq.pop();
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
30
Task/Priority-queue/C++/priority-queue-2.cpp
Normal file
30
Task/Priority-queue/C++/priority-queue-2.cpp
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
#include <iostream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
#include <utility>
|
||||
|
||||
int main() {
|
||||
std::vector<std::pair<int, std::string> > pq;
|
||||
pq.push_back(std::make_pair(3, "Clear drains"));
|
||||
pq.push_back(std::make_pair(4, "Feed cat"));
|
||||
pq.push_back(std::make_pair(5, "Make tea"));
|
||||
pq.push_back(std::make_pair(1, "Solve RC tasks"));
|
||||
|
||||
// heapify
|
||||
std::make_heap(pq.begin(), pq.end());
|
||||
|
||||
// enqueue
|
||||
pq.push_back(std::make_pair(2, "Tax return"));
|
||||
std::push_heap(pq.begin(), pq.end());
|
||||
|
||||
while (!pq.empty()) {
|
||||
// peek
|
||||
std::cout << pq[0].first << ", " << pq[0].second << std::endl;
|
||||
// dequeue
|
||||
std::pop_heap(pq.begin(), pq.end());
|
||||
pq.pop_back();
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
131
Task/Priority-queue/C/priority-queue-1.c
Normal file
131
Task/Priority-queue/C/priority-queue-1.c
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
typedef struct { void * data; int pri; } q_elem_t;
|
||||
typedef struct { q_elem_t *buf; int n, alloc; } pri_queue_t, *pri_queue;
|
||||
|
||||
#define priq_purge(q) (q)->n = 1
|
||||
#define priq_size(q) ((q)->n - 1)
|
||||
/* first element in array not used to simplify indices */
|
||||
pri_queue priq_new(int size)
|
||||
{
|
||||
if (size < 4) size = 4;
|
||||
|
||||
pri_queue q = malloc(sizeof(pri_queue_t));
|
||||
q->buf = malloc(sizeof(q_elem_t) * size);
|
||||
q->alloc = size;
|
||||
q->n = 1;
|
||||
|
||||
return q;
|
||||
}
|
||||
|
||||
void priq_push(pri_queue q, void *data, int pri)
|
||||
{
|
||||
q_elem_t *b;
|
||||
int n, m;
|
||||
|
||||
if (q->n >= q->alloc) {
|
||||
q->alloc *= 2;
|
||||
b = q->buf = realloc(q->buf, sizeof(q_elem_t) * q->alloc);
|
||||
} else
|
||||
b = q->buf;
|
||||
|
||||
n = q->n++;
|
||||
/* append at end, then up heap */
|
||||
while ((m = n / 2) && pri < b[m].pri) {
|
||||
b[n] = b[m];
|
||||
n = m;
|
||||
}
|
||||
b[n].data = data;
|
||||
b[n].pri = pri;
|
||||
}
|
||||
|
||||
/* remove top item. returns 0 if empty. *pri can be null. */
|
||||
void * priq_pop(pri_queue q, int *pri)
|
||||
{
|
||||
void *out;
|
||||
if (q->n == 1) return 0;
|
||||
|
||||
q_elem_t *b = q->buf;
|
||||
|
||||
out = b[1].data;
|
||||
if (pri) *pri = b[1].pri;
|
||||
|
||||
/* pull last item to top, then down heap. */
|
||||
--q->n;
|
||||
|
||||
int n = 1, m;
|
||||
while ((m = n * 2) < q->n) {
|
||||
if (m + 1 < q->n && b[m].pri > b[m + 1].pri) m++;
|
||||
|
||||
if (b[q->n].pri <= b[m].pri) break;
|
||||
b[n] = b[m];
|
||||
n = m;
|
||||
}
|
||||
|
||||
b[n] = b[q->n];
|
||||
if (q->n < q->alloc / 2 && q->n >= 16)
|
||||
q->buf = realloc(q->buf, (q->alloc /= 2) * sizeof(b[0]));
|
||||
|
||||
return out;
|
||||
}
|
||||
|
||||
/* get the top element without removing it from queue */
|
||||
void* priq_top(pri_queue q, int *pri)
|
||||
{
|
||||
if (q->n == 1) return 0;
|
||||
if (pri) *pri = q->buf[1].pri;
|
||||
return q->buf[1].data;
|
||||
}
|
||||
|
||||
/* this is O(n log n), but probably not the best */
|
||||
void priq_combine(pri_queue q, pri_queue q2)
|
||||
{
|
||||
int i;
|
||||
q_elem_t *e = q2->buf + 1;
|
||||
|
||||
for (i = q2->n - 1; i >= 1; i--, e++)
|
||||
priq_push(q, e->data, e->pri);
|
||||
priq_purge(q2);
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
int i, p;
|
||||
const char *c, *tasks[] ={
|
||||
"Clear drains", "Feed cat", "Make tea", "Solve RC tasks", "Tax return" };
|
||||
int pri[] = { 3, 4, 5, 1, 2 };
|
||||
|
||||
/* make two queues */
|
||||
pri_queue q = priq_new(0), q2 = priq_new(0);
|
||||
|
||||
/* push all 5 tasks into q */
|
||||
for (i = 0; i < 5; i++)
|
||||
priq_push(q, tasks[i], pri[i]);
|
||||
|
||||
/* pop them and print one by one */
|
||||
while ((c = priq_pop(q, &p)))
|
||||
printf("%d: %s\n", p, c);
|
||||
|
||||
/* put a million random tasks in each queue */
|
||||
for (i = 0; i < 1 << 20; i++) {
|
||||
p = rand() / ( RAND_MAX / 5 );
|
||||
priq_push(q, tasks[p], pri[p]);
|
||||
|
||||
p = rand() / ( RAND_MAX / 5 );
|
||||
priq_push(q2, tasks[p], pri[p]);
|
||||
}
|
||||
|
||||
printf("\nq has %d items, q2 has %d items\n", priq_size(q), priq_size(q2));
|
||||
|
||||
/* merge q2 into q; q2 is empty */
|
||||
priq_combine(q, q2);
|
||||
printf("After merge, q has %d items, q2 has %d items\n",
|
||||
priq_size(q), priq_size(q2));
|
||||
|
||||
/* pop q until it's empty */
|
||||
for (i = 0; (c = priq_pop(q, 0)); i++);
|
||||
printf("Popped %d items out of q\n", i);
|
||||
|
||||
return 0;
|
||||
}
|
||||
9
Task/Priority-queue/C/priority-queue-2.c
Normal file
9
Task/Priority-queue/C/priority-queue-2.c
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
1: Solve RC tasks
|
||||
2: Tax return
|
||||
3: Clear drains
|
||||
4: Feed cat
|
||||
5: Make tea
|
||||
|
||||
q has 1048576 items, q2 has 1048576 items
|
||||
After merge, q has 2097152 items, q2 has 0 items
|
||||
Popped 2097152 items out of q
|
||||
|
|
@ -0,0 +1,78 @@
|
|||
PriorityQueue = ->
|
||||
# Use closure style for object creation (so no "new" required).
|
||||
# Private variables are toward top.
|
||||
h = []
|
||||
|
||||
better = (a, b) ->
|
||||
h[a].priority < h[b].priority
|
||||
|
||||
swap = (a, b) ->
|
||||
[h[a], h[b]] = [h[b], h[a]]
|
||||
|
||||
sift_down = ->
|
||||
max = h.length
|
||||
n = 0
|
||||
while n < max
|
||||
c1 = 2*n + 1
|
||||
c2 = c1 + 1
|
||||
best = n
|
||||
best = c1 if c1 < max and better(c1, best)
|
||||
best = c2 if c2 < max and better(c2, best)
|
||||
return if best == n
|
||||
swap n, best
|
||||
n = best
|
||||
|
||||
sift_up = ->
|
||||
n = h.length - 1
|
||||
while n > 0
|
||||
parent = Math.floor((n-1) / 2)
|
||||
return if better parent, n
|
||||
swap n, parent
|
||||
n = parent
|
||||
|
||||
# now return the public interface, which is an object that only
|
||||
# has functions on it
|
||||
self =
|
||||
size: ->
|
||||
h.length
|
||||
|
||||
push: (priority, value) ->
|
||||
elem =
|
||||
priority: priority
|
||||
value: value
|
||||
h.push elem
|
||||
sift_up()
|
||||
|
||||
pop: ->
|
||||
throw Error("cannot pop from empty queue") if h.length == 0
|
||||
value = h[0].value
|
||||
last = h.pop()
|
||||
if h.length > 0
|
||||
h[0] = last
|
||||
sift_down()
|
||||
value
|
||||
|
||||
# test
|
||||
do ->
|
||||
pq = PriorityQueue()
|
||||
pq.push 3, "Clear drains"
|
||||
pq.push 4, "Feed cat"
|
||||
pq.push 5, "Make tea"
|
||||
pq.push 1, "Solve RC tasks"
|
||||
pq.push 2, "Tax return"
|
||||
|
||||
while pq.size() > 0
|
||||
console.log pq.pop()
|
||||
|
||||
# test high performance
|
||||
for n in [1..100000]
|
||||
priority = Math.random()
|
||||
pq.push priority, priority
|
||||
|
||||
v = pq.pop()
|
||||
console.log "First random element was #{v}"
|
||||
while pq.size() > 0
|
||||
new_v = pq.pop()
|
||||
throw Error "Queue broken" if new_v < v
|
||||
v = new_v
|
||||
console.log "Final random element was #{v}"
|
||||
|
|
@ -0,0 +1,8 @@
|
|||
> coffee priority_queue.coffee
|
||||
Solve RC tasks
|
||||
Tax return
|
||||
Clear drains
|
||||
Feed cat
|
||||
Make tea
|
||||
First random element was 0.00002744467929005623
|
||||
Final random element was 0.9999718656763434
|
||||
15
Task/Priority-queue/D/priority-queue.d
Normal file
15
Task/Priority-queue/D/priority-queue.d
Normal file
|
|
@ -0,0 +1,15 @@
|
|||
import std.stdio, std.container, std.array, std.typecons;
|
||||
|
||||
void main() {
|
||||
alias tuple T;
|
||||
auto heap = heapify([T(3, "Clear drains"),
|
||||
T(4, "Feed cat"),
|
||||
T(5, "Make tea"),
|
||||
T(1, "Solve RC tasks"),
|
||||
T(2, "Tax return")]);
|
||||
|
||||
while (!heap.empty) {
|
||||
writeln(heap.front);
|
||||
heap.removeFront();
|
||||
}
|
||||
}
|
||||
10
Task/Priority-queue/Factor/priority-queue-1.factor
Normal file
10
Task/Priority-queue/Factor/priority-queue-1.factor
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
<min-heap> [ {
|
||||
{ 3 "Clear drains" }
|
||||
{ 4 "Feed cat" }
|
||||
{ 5 "Make tea" }
|
||||
{ 1 "Solve RC tasks" }
|
||||
{ 2 "Tax return" }
|
||||
} swap heap-push-all
|
||||
] [
|
||||
[ print ] slurp-heap
|
||||
] bi
|
||||
5
Task/Priority-queue/Factor/priority-queue-2.factor
Normal file
5
Task/Priority-queue/Factor/priority-queue-2.factor
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
Solve RC tasks
|
||||
Tax return
|
||||
Clear drains
|
||||
Feed cat
|
||||
Make tea
|
||||
43
Task/Priority-queue/Go/priority-queue.go
Normal file
43
Task/Priority-queue/Go/priority-queue.go
Normal file
|
|
@ -0,0 +1,43 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"container/heap"
|
||||
)
|
||||
|
||||
type Task struct {
|
||||
priority int
|
||||
name string
|
||||
}
|
||||
|
||||
type TaskPQ []Task
|
||||
|
||||
func (self TaskPQ) Len() int { return len(self) }
|
||||
func (self TaskPQ) Less(i, j int) bool {
|
||||
return self[i].priority < self[j].priority
|
||||
}
|
||||
func (self TaskPQ) Swap(i, j int) { self[i], self[j] = self[j], self[i] }
|
||||
func (self *TaskPQ) Push(x interface{}) { *self = append(*self, x.(Task)) }
|
||||
func (self *TaskPQ) Pop() (popped interface{}) {
|
||||
popped = (*self)[len(*self)-1]
|
||||
*self = (*self)[:len(*self)-1]
|
||||
return
|
||||
}
|
||||
|
||||
func main() {
|
||||
pq := &TaskPQ{{3, "Clear drains"},
|
||||
{4, "Feed cat"},
|
||||
{5, "Make tea"},
|
||||
{1, "Solve RC tasks"}}
|
||||
|
||||
// heapify
|
||||
heap.Init(pq)
|
||||
|
||||
// enqueue
|
||||
heap.Push(pq, Task{2, "Tax return"})
|
||||
|
||||
for pq.Len() != 0 {
|
||||
// dequeue
|
||||
fmt.Println(heap.Pop(pq))
|
||||
}
|
||||
}
|
||||
3
Task/Priority-queue/Haskell/priority-queue-1.hs
Normal file
3
Task/Priority-queue/Haskell/priority-queue-1.hs
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
import Data.PQueue.Prio.Min
|
||||
|
||||
main = print (toList (fromList [(3, "Clear drains"),(4, "Feed cat"),(5, "Make tea"),(1, "Solve RC tasks"), (2, "Tax return")]))
|
||||
44
Task/Priority-queue/Haskell/priority-queue-2.hs
Normal file
44
Task/Priority-queue/Haskell/priority-queue-2.hs
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
data MinHeap a = Nil | MinHeap { v::a, cnt::Int, l::MinHeap a, r::MinHeap a }
|
||||
deriving (Show, Eq)
|
||||
|
||||
hPush :: (Ord a) => a -> MinHeap a -> MinHeap a
|
||||
hPush x Nil = MinHeap {v = x, cnt = 1, l = Nil, r = Nil}
|
||||
hPush x h = if x < vv -- insert element, try to keep the tree balanced
|
||||
then if hLength (l h) <= hLength (r h)
|
||||
then MinHeap { v=x, cnt=cc, l=hPush vv ll, r=rr }
|
||||
else MinHeap { v=x, cnt=cc, l=ll, r=hPush vv rr }
|
||||
else if hLength (l h) <= hLength (r h)
|
||||
then MinHeap { v=vv, cnt=cc, l=hPush x ll, r=rr }
|
||||
else MinHeap { v=vv, cnt=cc, l=ll, r=hPush x rr }
|
||||
where (vv, cc, ll, rr) = (v h, 1 + cnt h, l h, r h)
|
||||
|
||||
hPop :: (Ord a) => MinHeap a -> (a, MinHeap a)
|
||||
hPop h = (v h, pq) where -- just pop, heed not the tree balance
|
||||
pq | l h == Nil = r h
|
||||
| r h == Nil = l h
|
||||
| v (l h) <= v (r h) = let (vv,hh) = hPop (l h) in
|
||||
MinHeap {v = vv, cnt = hLength hh + hLength (r h),
|
||||
l = hh, r = r h}
|
||||
| otherwise = let (vv,hh) = hPop (r h) in
|
||||
MinHeap {v = vv, cnt = hLength hh + hLength (l h),
|
||||
l = l h, r = hh}
|
||||
|
||||
hLength :: (Ord a) => MinHeap a -> Int
|
||||
hLength Nil = 0
|
||||
hLength h = cnt h
|
||||
|
||||
hFromList :: (Ord a) => [a] -> MinHeap a
|
||||
hFromList xs = hlist Nil xs where
|
||||
hlist h [] = h
|
||||
hlist h (x:xs) = hlist (hPush x h) xs
|
||||
|
||||
hToList :: (Ord a) => MinHeap a -> [a]
|
||||
hToList Nil = []
|
||||
hToList h = x:hToList hh where (x,hh) = hPop h
|
||||
|
||||
main = mapM print $ (hToList (hFromList [
|
||||
(3, "Clear drains"),
|
||||
(4, "Feed cat"),
|
||||
(5, "Make tea"),
|
||||
(1, "Solve RC tasks"),
|
||||
(2, "Tax return")]))
|
||||
13
Task/Priority-queue/Icon/priority-queue.icon
Normal file
13
Task/Priority-queue/Icon/priority-queue.icon
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import Utils # For Closure class
|
||||
import Collections # For Heap (dense priority queue) class
|
||||
|
||||
procedure main()
|
||||
pq := Heap(, Closure("[]",Arg,1) )
|
||||
pq.add([3, "Clear drains"])
|
||||
pq.add([4, "Feed cat"])
|
||||
pq.add([5, "Make tea"])
|
||||
pq.add([1, "Solve RC tasks"])
|
||||
pq.add([2, "Tax return"])
|
||||
|
||||
while task := pq.get() do write(task[1]," -> ",task[2])
|
||||
end
|
||||
23
Task/Priority-queue/J/priority-queue-1.j
Normal file
23
Task/Priority-queue/J/priority-queue-1.j
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
coclass 'priorityQueue'
|
||||
|
||||
PRI=: ''
|
||||
QUE=: ''
|
||||
|
||||
insert=:4 :0
|
||||
p=. PRI,x
|
||||
q=. QUE,y
|
||||
assert. p -:&$ q
|
||||
assert. 1 = #$q
|
||||
ord=: \: p
|
||||
QUE=: ord { q
|
||||
PRI=: ord { p
|
||||
i.0 0
|
||||
)
|
||||
|
||||
topN=:3 :0
|
||||
assert y<:#PRI
|
||||
r=. y{.QUE
|
||||
PRI=: y}.PRI
|
||||
QUE=: y}.QUE
|
||||
r
|
||||
)
|
||||
9
Task/Priority-queue/J/priority-queue-2.j
Normal file
9
Task/Priority-queue/J/priority-queue-2.j
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
Q=: conew'priorityQueue'
|
||||
3 4 5 1 2 insert__Q 'clear drains';'feed cat';'make tea';'solve rc task';'tax return'
|
||||
>topN__Q 1
|
||||
make tea
|
||||
>topN__Q 4
|
||||
feed cat
|
||||
clear drains
|
||||
tax return
|
||||
solve rc task
|
||||
31
Task/Priority-queue/Java/priority-queue.java
Normal file
31
Task/Priority-queue/Java/priority-queue.java
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import java.util.PriorityQueue;
|
||||
|
||||
class Task implements Comparable<Task> {
|
||||
final int priority;
|
||||
final String name;
|
||||
|
||||
public Task(int p, String n) {
|
||||
priority = p;
|
||||
name = n;
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return priority + ", " + name;
|
||||
}
|
||||
|
||||
public int compareTo(Task other) {
|
||||
return priority < other.priority ? -1 : priority > other.priority ? 1 : 0;
|
||||
}
|
||||
|
||||
public static final void main(String[] args) {
|
||||
PriorityQueue<Task> pq = new PriorityQueue<Task>();
|
||||
pq.add(new Task(3, "Clear drains"));
|
||||
pq.add(new Task(4, "Feed cat"));
|
||||
pq.add(new Task(5, "Make tea"));
|
||||
pq.add(new Task(1, "Solve RC tasks"));
|
||||
pq.add(new Task(2, "Tax return"));
|
||||
|
||||
while (!pq.isEmpty())
|
||||
System.out.println(pq.remove());
|
||||
}
|
||||
}
|
||||
10
Task/Priority-queue/Mathematica/priority-queue-1.math
Normal file
10
Task/Priority-queue/Mathematica/priority-queue-1.math
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
push = Function[{queue, priority, item},
|
||||
queue = SortBy[Append[queue, {priority, item}], First], HoldFirst];
|
||||
pop = Function[queue,
|
||||
If[Length@queue == 0, Null,
|
||||
With[{item = queue[[-1, 2]]}, queue = Most@queue; item]],
|
||||
HoldFirst];
|
||||
peek = Function[queue,
|
||||
If[Length@queue == 0, Null, Max[queue[[All, 1]]]], HoldFirst];
|
||||
merge = Function[{queue1, queue2},
|
||||
SortBy[Join[queue1, queue2], First], HoldAll];
|
||||
11
Task/Priority-queue/Mathematica/priority-queue-2.math
Normal file
11
Task/Priority-queue/Mathematica/priority-queue-2.math
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
queue = {};
|
||||
push[queue, 3, "Clear drains"];
|
||||
push[queue, 4, "Feed cat"];
|
||||
push[queue, 5, "Make tea"];
|
||||
push[queue, 1, "Solve RC tasks"];
|
||||
push[queue, 2, "Tax return"];
|
||||
Print[peek[queue]];
|
||||
Print[pop[queue]];
|
||||
queue1 = {};
|
||||
push[queue1, 6, "Drink tea"];
|
||||
Print[merge[queue, queue1]];
|
||||
82
Task/Priority-queue/Maxima/priority-queue.maxima
Normal file
82
Task/Priority-queue/Maxima/priority-queue.maxima
Normal file
|
|
@ -0,0 +1,82 @@
|
|||
/* Naive implementation using a sorted list of pairs [key, [item[1], ..., item[n]]].
|
||||
The key may be any number (integer or not). Items are extracted in FIFO order. */
|
||||
|
||||
defstruct(pqueue(q = []))$
|
||||
|
||||
/* Binary search */
|
||||
|
||||
find_key(q, p) := block(
|
||||
[i: 1, j: length(q), k, c],
|
||||
if j = 0 then false
|
||||
elseif (c: q[i][1]) >= p then
|
||||
(if c = p then i else false)
|
||||
elseif (c: q[j][1]) <= p then
|
||||
(if c = p then j else false)
|
||||
else catch(
|
||||
while j >= i do (
|
||||
k: quotient(i + j, 2),
|
||||
if (c: q[k][1]) = p then throw(k)
|
||||
elseif c < p then i: k + 1 else j: k - 1
|
||||
),
|
||||
false
|
||||
)
|
||||
)$
|
||||
|
||||
pqueue_push(pq, x, p) := block(
|
||||
[q: pq@q, k],
|
||||
k: find_key(q, p),
|
||||
if integerp(k) then q[k][2]: endcons(x, q[k][2])
|
||||
else pq@q: sort(cons([p, [x]], q)),
|
||||
'done
|
||||
)$
|
||||
|
||||
pqueue_pop(pq) := block(
|
||||
[q: pq@q, v, x],
|
||||
if emptyp(q) then 'fail else (
|
||||
p: q[1][1],
|
||||
v: q[1][2],
|
||||
x: v[1],
|
||||
if length(v) > 1 then q[1][2]: rest(v) else pq@q: rest(q),
|
||||
x
|
||||
)
|
||||
)$
|
||||
|
||||
pqueue_print(pq) := block([t], while (t: pqueue_pop(pq)) # 'fail do disp(t))$
|
||||
|
||||
|
||||
/* An example */
|
||||
|
||||
a: new(pqueue)$
|
||||
|
||||
pqueue_push(a, "take milk", 4)$
|
||||
pqueue_push(a, "take eggs", 4)$
|
||||
pqueue_push(a, "take wheat flour", 4)$
|
||||
pqueue_push(a, "take salt", 4)$
|
||||
pqueue_push(a, "take oil", 4)$
|
||||
pqueue_push(a, "carry out crepe recipe", 5)$
|
||||
pqueue_push(a, "savour !", 6)$
|
||||
pqueue_push(a, "add strawberry jam", 5 + 1/2)$
|
||||
pqueue_push(a, "call friends", 5 + 2/3)$
|
||||
pqueue_push(a, "go to the supermarket and buy food", 3)$
|
||||
pqueue_push(a, "take a shower", 2)$
|
||||
pqueue_push(a, "get dressed", 2)$
|
||||
pqueue_push(a, "wake up", 1)$
|
||||
pqueue_push(a, "serve cider", 5 + 3/4)$
|
||||
pqueue_push(a, "buy also cider", 3)$
|
||||
|
||||
pqueue_print(a);
|
||||
"wake up"
|
||||
"take a shower"
|
||||
"get dressed"
|
||||
"go to the supermarket and buy food"
|
||||
"buy also cider"
|
||||
"take milk"
|
||||
"take butter"
|
||||
"take flour"
|
||||
"take salt"
|
||||
"take oil"
|
||||
"carry out recipe"
|
||||
"add strawberry jam"
|
||||
"call friends"
|
||||
"serve cider"
|
||||
"savour !"
|
||||
17
Task/Priority-queue/OCaml/priority-queue-1.ocaml
Normal file
17
Task/Priority-queue/OCaml/priority-queue-1.ocaml
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
module PQ = Base.PriorityQueue
|
||||
|
||||
let () =
|
||||
let tasks = [
|
||||
3, "Clear drains";
|
||||
4, "Feed cat";
|
||||
5, "Make tea";
|
||||
1, "Solve RC tasks";
|
||||
2, "Tax return";
|
||||
] in
|
||||
let pq = PQ.make (fun (prio1, _) (prio2, _) -> prio1 > prio2) in
|
||||
List.iter (PQ.add pq) tasks;
|
||||
while not (PQ.is_empty pq) do
|
||||
let _, task = PQ.first pq in
|
||||
PQ.remove_first pq;
|
||||
print_endline task
|
||||
done
|
||||
22
Task/Priority-queue/OCaml/priority-queue-2.ocaml
Normal file
22
Task/Priority-queue/OCaml/priority-queue-2.ocaml
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
module PQSet = Set.Make
|
||||
(struct
|
||||
type t = int * string (* pair of priority and task name *)
|
||||
let compare = compare
|
||||
end);;
|
||||
|
||||
let () =
|
||||
let tasks = [
|
||||
3, "Clear drains";
|
||||
4, "Feed cat";
|
||||
5, "Make tea";
|
||||
1, "Solve RC tasks";
|
||||
2, "Tax return";
|
||||
] in
|
||||
let pq = List.fold_right PQSet.add tasks PQSet.empty in
|
||||
let rec aux pq' =
|
||||
if not (PQSet.is_empty pq') then begin
|
||||
let prio, name as task = PQSet.min_elt pq' in
|
||||
Printf.printf "%d, %s\n" prio name;
|
||||
aux (PQSet.remove task pq')
|
||||
end
|
||||
in aux pq
|
||||
68
Task/Priority-queue/Objective-C/priority-queue.m
Normal file
68
Task/Priority-queue/Objective-C/priority-queue.m
Normal file
|
|
@ -0,0 +1,68 @@
|
|||
#import <Foundation/Foundation.h>
|
||||
|
||||
const void *PQRetain(CFAllocatorRef allocator, const void *ptr) {
|
||||
return [(id)ptr retain];
|
||||
}
|
||||
void PQRelease(CFAllocatorRef allocator, const void *ptr) {
|
||||
[(id)ptr release];
|
||||
}
|
||||
CFComparisonResult PQCompare(const void *ptr1, const void *ptr2, void *unused) {
|
||||
return [(id)ptr1 compare:(id)ptr2];
|
||||
}
|
||||
|
||||
@interface Task : NSObject {
|
||||
int priority;
|
||||
NSString *name;
|
||||
}
|
||||
- (id)initWithPriority:(int)p andName:(NSString *)n;
|
||||
- (NSComparisonResult)compare:(Task *)other;
|
||||
@end
|
||||
|
||||
@implementation Task
|
||||
- (id)initWithPriority:(int)p andName:(NSString *)n {
|
||||
if ((self = [super init])) {
|
||||
priority = p;
|
||||
name = [n copy];
|
||||
}
|
||||
return self;
|
||||
}
|
||||
- (void)dealloc {
|
||||
[name release];
|
||||
[super dealloc];
|
||||
}
|
||||
- (NSString *)description {
|
||||
return [NSString stringWithFormat:@"%d, %@", priority, name];
|
||||
}
|
||||
- (NSComparisonResult)compare:(Task *)other {
|
||||
if (priority == other->priority)
|
||||
return NSOrderedSame;
|
||||
else if (priority < other->priority)
|
||||
return NSOrderedAscending;
|
||||
else
|
||||
return NSOrderedDescending;
|
||||
}
|
||||
@end
|
||||
|
||||
int main (int argc, const char *argv[]) {
|
||||
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
|
||||
|
||||
CFBinaryHeapCallBacks callBacks = {0, PQRetain, PQRelease, NULL, PQCompare};
|
||||
CFBinaryHeapRef pq = CFBinaryHeapCreate(NULL, 0, &callBacks, NULL);
|
||||
|
||||
CFBinaryHeapAddValue(pq, [[[Task alloc] initWithPriority:3 andName:@"Clear drains"] autorelease]);
|
||||
CFBinaryHeapAddValue(pq, [[[Task alloc] initWithPriority:4 andName:@"Feed cat"] autorelease]);
|
||||
CFBinaryHeapAddValue(pq, [[[Task alloc] initWithPriority:5 andName:@"Make tea"] autorelease]);
|
||||
CFBinaryHeapAddValue(pq, [[[Task alloc] initWithPriority:1 andName:@"Solve RC tasks"] autorelease]);
|
||||
CFBinaryHeapAddValue(pq, [[[Task alloc] initWithPriority:2 andName:@"Tax return"] autorelease]);
|
||||
|
||||
while (CFBinaryHeapGetCount(pq) != 0) {
|
||||
Task *task = (id)CFBinaryHeapGetMinimum(pq);
|
||||
NSLog(@"%@", task);
|
||||
CFBinaryHeapRemoveMinimumValue(pq);
|
||||
}
|
||||
|
||||
CFRelease(pq);
|
||||
|
||||
[pool drain];
|
||||
return 0;
|
||||
}
|
||||
17
Task/Priority-queue/PHP/priority-queue-1.php
Normal file
17
Task/Priority-queue/PHP/priority-queue-1.php
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
<?php
|
||||
$pq = new SplPriorityQueue;
|
||||
|
||||
$pq->insert('Clear drains', 3);
|
||||
$pq->insert('Feed cat', 4);
|
||||
$pq->insert('Make tea', 5);
|
||||
$pq->insert('Solve RC tasks', 1);
|
||||
$pq->insert('Tax return', 2);
|
||||
|
||||
// This line causes extract() to return both the data and priority (in an associative array),
|
||||
// Otherwise it would just return the data
|
||||
$pq->setExtractFlags(SplPriorityQueue::EXTR_BOTH);
|
||||
|
||||
while (!$pq->isEmpty()) {
|
||||
print_r($pq->extract());
|
||||
}
|
||||
?>
|
||||
13
Task/Priority-queue/PHP/priority-queue-2.php
Normal file
13
Task/Priority-queue/PHP/priority-queue-2.php
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
<?php
|
||||
$pq = new SplMinHeap;
|
||||
|
||||
$pq->insert(array(3, 'Clear drains'));
|
||||
$pq->insert(array(4, 'Feed cat'));
|
||||
$pq->insert(array(5, 'Make tea'));
|
||||
$pq->insert(array(1, 'Solve RC tasks'));
|
||||
$pq->insert(array(2, 'Tax return'));
|
||||
|
||||
while (!$pq->isEmpty()) {
|
||||
print_r($pq->extract());
|
||||
}
|
||||
?>
|
||||
29
Task/Priority-queue/Perl-6/priority-queue.pl6
Normal file
29
Task/Priority-queue/Perl-6/priority-queue.pl6
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
class PriorityQueue {
|
||||
has @!tasks is rw;
|
||||
|
||||
method insert ( Int $priority where { $priority >= 0 }, $task ) {
|
||||
@!tasks[$priority] //= [];
|
||||
@!tasks[$priority].push: $task;
|
||||
}
|
||||
|
||||
method get { @!tasks.first({$^_}).shift }
|
||||
|
||||
method is_empty { !?@!tasks.first({$^_}) }
|
||||
}
|
||||
|
||||
my $pq = PriorityQueue.new;
|
||||
|
||||
for (
|
||||
3, 'Clear drains',
|
||||
4, 'Feed cat',
|
||||
5, 'Make tea',
|
||||
9, 'Sleep',
|
||||
3, 'Check email',
|
||||
1, 'Solve RC tasks',
|
||||
9, 'Exercise',
|
||||
2, 'Do taxes'
|
||||
) -> $priority, $task {
|
||||
$pq.insert( $priority, $task );
|
||||
}
|
||||
|
||||
say $pq.get until $pq.is_empty;
|
||||
14
Task/Priority-queue/Perl/priority-queue-1.pl
Normal file
14
Task/Priority-queue/Perl/priority-queue-1.pl
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
use 5.10.0;
|
||||
use strict;
|
||||
use Heap::Priority;
|
||||
|
||||
my $h = new Heap::Priority;
|
||||
|
||||
$h->highest_first(); # higher or lower number is more important
|
||||
$h->add(@$_) for ["Clear drains", 3],
|
||||
["Feed cat", 4],
|
||||
["Make tea", 5],
|
||||
["Solve RC tasks", 1],
|
||||
["Tax return", 2];
|
||||
|
||||
say while ($_ = $h->pop);
|
||||
5
Task/Priority-queue/Perl/priority-queue-2.pl
Normal file
5
Task/Priority-queue/Perl/priority-queue-2.pl
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
Make tea
|
||||
Feed cat
|
||||
Clear drains
|
||||
Tax return
|
||||
Solve RC tasks
|
||||
18
Task/Priority-queue/PicoLisp/priority-queue-1.l
Normal file
18
Task/Priority-queue/PicoLisp/priority-queue-1.l
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
# Insert item into priority queue
|
||||
(de insertPQ (Queue Prio Item)
|
||||
(idx Queue (cons Prio Item) T) )
|
||||
|
||||
# Remove and return top item from priority queue
|
||||
(de removePQ (Queue)
|
||||
(cdar (idx Queue (peekPQ Queue) NIL)) )
|
||||
|
||||
# Find top element in priority queue
|
||||
(de peekPQ (Queue)
|
||||
(let V (val Queue)
|
||||
(while (cadr V)
|
||||
(setq V @) )
|
||||
(car V) ) )
|
||||
|
||||
# Merge second queue into first
|
||||
(de mergePQ (Queue1 Queue2)
|
||||
(balance Queue1 (sort (conc (idx Queue1) (idx Queue2)))) )
|
||||
18
Task/Priority-queue/PicoLisp/priority-queue-2.l
Normal file
18
Task/Priority-queue/PicoLisp/priority-queue-2.l
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
# Two priority queues
|
||||
(off Pq1 Pq2)
|
||||
|
||||
# Insert into first queue
|
||||
(insertPQ 'Pq1 3 '(Clear drains))
|
||||
(insertPQ 'Pq1 4 '(Feed cat))
|
||||
|
||||
# Insert into second queue
|
||||
(insertPQ 'Pq2 5 '(Make tea))
|
||||
(insertPQ 'Pq2 1 '(Solve RC tasks))
|
||||
(insertPQ 'Pq2 2 '(Tax return))
|
||||
|
||||
# Merge second into first queue
|
||||
(mergePQ 'Pq1 'Pq2)
|
||||
|
||||
# Remove and print all items from first queue
|
||||
(while Pq1
|
||||
(println (removePQ 'Pq1)) )
|
||||
28
Task/Priority-queue/Prolog/priority-queue.pro
Normal file
28
Task/Priority-queue/Prolog/priority-queue.pro
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
priority-queue :-
|
||||
TL0 = [3-'Clear drains',
|
||||
4-'Feed cat'],
|
||||
|
||||
% we can create a priority queue from a list
|
||||
list_to_heap(TL0, Heap0),
|
||||
|
||||
% alternatively we can start from an empty queue
|
||||
% get from empty_heap/1.
|
||||
|
||||
% now we add the other elements
|
||||
add_to_heap(Heap0, 5, 'Make tea', Heap1),
|
||||
add_to_heap(Heap1, 1, 'Solve RC tasks', Heap2),
|
||||
add_to_heap(Heap2, 2, 'Tax return', Heap3),
|
||||
|
||||
% we list the content of the heap:
|
||||
heap_to_list(Heap3, TL1),
|
||||
writeln('Content of the queue'), maplist(writeln, TL1),
|
||||
nl,
|
||||
|
||||
% now we retrieve the minimum-priority pair
|
||||
get_from_heap(Heap3, Priority, Key, Heap4),
|
||||
format('Retrieve top of the queue : Priority ~w, Element ~w~n', [Priority, Key]),
|
||||
nl,
|
||||
|
||||
% we list the content of the heap:
|
||||
heap_to_list(Heap4, TL2),
|
||||
writeln('Content of the queue'), maplist(writeln, TL2).
|
||||
119
Task/Priority-queue/PureBasic/priority-queue.purebasic
Normal file
119
Task/Priority-queue/PureBasic/priority-queue.purebasic
Normal file
|
|
@ -0,0 +1,119 @@
|
|||
Structure taskList
|
||||
List description.s() ;implements FIFO queue
|
||||
EndStructure
|
||||
|
||||
Structure task
|
||||
*tl.tList ;pointer to a list of task descriptions
|
||||
Priority.i ;tasks priority, lower value has more priority
|
||||
EndStructure
|
||||
|
||||
Structure priorityQueue
|
||||
maxHeapSize.i ;increases as needed
|
||||
heapItemCount.i ;number of elements currently in heap
|
||||
Array heap.task(0) ;elements hold FIFO queues ordered by priorities, lowest first
|
||||
map heapMap.taskList() ;holds lists of tasks with the same priority that are FIFO queues
|
||||
EndStructure
|
||||
|
||||
Procedure insertPQ(*PQ.priorityQueue, description.s, p)
|
||||
If FindMapElement(*PQ\heapMap(), Str(p))
|
||||
LastElement(*PQ\heapMap()\description())
|
||||
AddElement(*PQ\heapMap()\description())
|
||||
*PQ\heapMap()\description() = description
|
||||
Else
|
||||
Protected *tl.taskList = AddMapElement(*PQ\heapMap(), Str(p))
|
||||
AddElement(*tl\description())
|
||||
*tl\description() = description
|
||||
|
||||
Protected pos = *PQ\heapItemCount
|
||||
|
||||
*PQ\heapItemCount + 1
|
||||
If *PQ\heapItemCount > *PQ\maxHeapSize
|
||||
Select *PQ\maxHeapSize
|
||||
Case 0
|
||||
*PQ\maxHeapSize = 128
|
||||
Default
|
||||
*PQ\maxHeapSize * 2
|
||||
EndSelect
|
||||
Redim *PQ\heap.task(*PQ\maxHeapSize)
|
||||
EndIf
|
||||
|
||||
While pos > 0 And p < *PQ\heap((pos - 1) / 2)\Priority
|
||||
*PQ\heap(pos) = *PQ\heap((pos - 1) / 2)
|
||||
pos = (pos - 1) / 2
|
||||
Wend
|
||||
|
||||
*PQ\heap(pos)\tl = *tl
|
||||
*PQ\heap(pos)\Priority = p
|
||||
EndIf
|
||||
EndProcedure
|
||||
|
||||
Procedure.s removePQ(*PQ.priorityQueue)
|
||||
Protected *tl.taskList = *PQ\heap(0)\tl, description.s
|
||||
FirstElement(*tl\description())
|
||||
description = *tl\description()
|
||||
If ListSize(*tl\description()) > 1
|
||||
DeleteElement(*tl\description())
|
||||
Else
|
||||
DeleteMapElement(*PQ\heapMap(), Str(*PQ\heap(0)\Priority))
|
||||
|
||||
*PQ\heapItemCount - 1
|
||||
*PQ\heap(0) = *PQ\heap(*PQ\heapItemCount)
|
||||
|
||||
Protected pos
|
||||
Repeat
|
||||
Protected child1 = 2 * pos + 1
|
||||
Protected child2 = 2 * pos + 2
|
||||
If child1 >= *PQ\heapItemCount
|
||||
Break
|
||||
EndIf
|
||||
|
||||
Protected smallestChild
|
||||
If child2 >= *PQ\heapItemCount
|
||||
smallestChild = child1
|
||||
ElseIf *PQ\heap(child1)\Priority <= *PQ\heap(child2)\Priority
|
||||
smallestChild = child1
|
||||
Else
|
||||
smallestChild = child2
|
||||
EndIf
|
||||
|
||||
If (*PQ\heap(smallestChild)\Priority >= *PQ\heap(pos)\Priority)
|
||||
Break
|
||||
EndIf
|
||||
Swap *PQ\heap(pos)\tl, *PQ\heap(smallestChild)\tl
|
||||
Swap *PQ\heap(pos)\Priority, *PQ\heap(smallestChild)\Priority
|
||||
pos = smallestChild
|
||||
ForEver
|
||||
EndIf
|
||||
|
||||
ProcedureReturn description
|
||||
EndProcedure
|
||||
|
||||
Procedure isEmptyPQ(*PQ.priorityQueue) ;returns 1 if empty, otherwise returns 0
|
||||
If *PQ\heapItemCount
|
||||
ProcedureReturn 0
|
||||
EndIf
|
||||
ProcedureReturn 1
|
||||
EndProcedure
|
||||
|
||||
If OpenConsole()
|
||||
Define PQ.priorityQueue
|
||||
insertPQ(PQ, "Clear drains", 3)
|
||||
insertPQ(PQ, "Answer Phone 1", 8)
|
||||
insertPQ(PQ, "Feed cat", 4)
|
||||
insertPQ(PQ, "Answer Phone 2", 8)
|
||||
insertPQ(PQ, "Make tea", 5)
|
||||
insertPQ(PQ, "Sleep", 9)
|
||||
insertPQ(PQ, "Check email", 3)
|
||||
insertPQ(PQ, "Solve RC tasks", 1)
|
||||
insertPQ(PQ, "Answer Phone 3", 8)
|
||||
insertPQ(PQ, "Exercise", 9)
|
||||
insertPQ(PQ, "Answer Phone 4", 8)
|
||||
insertPQ(PQ, "Tax return", 2)
|
||||
|
||||
While Not isEmptyPQ(PQ)
|
||||
PrintN(removePQ(PQ))
|
||||
Wend
|
||||
|
||||
Print(#CRLF$ + #CRLF$ + "Press ENTER to exit"): Input()
|
||||
CloseConsole()
|
||||
EndIf
|
||||
16
Task/Priority-queue/Python/priority-queue-1.py
Normal file
16
Task/Priority-queue/Python/priority-queue-1.py
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
>>> import queue
|
||||
>>> pq = queue.PriorityQueue()
|
||||
>>> for item in ((3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")):
|
||||
pq.put(item)
|
||||
|
||||
|
||||
>>> while not pq.empty():
|
||||
print(pq.get_nowait())
|
||||
|
||||
|
||||
(1, 'Solve RC tasks')
|
||||
(2, 'Tax return')
|
||||
(3, 'Clear drains')
|
||||
(4, 'Feed cat')
|
||||
(5, 'Make tea')
|
||||
>>>
|
||||
107
Task/Priority-queue/Python/priority-queue-2.py
Normal file
107
Task/Priority-queue/Python/priority-queue-2.py
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
>>> import queue
|
||||
>>> help(queue.PriorityQueue)
|
||||
Help on class PriorityQueue in module queue:
|
||||
|
||||
class PriorityQueue(Queue)
|
||||
| Variant of Queue that retrieves open entries in priority order (lowest first).
|
||||
|
|
||||
| Entries are typically tuples of the form: (priority number, data).
|
||||
|
|
||||
| Method resolution order:
|
||||
| PriorityQueue
|
||||
| Queue
|
||||
| builtins.object
|
||||
|
|
||||
| Methods inherited from Queue:
|
||||
|
|
||||
| __init__(self, maxsize=0)
|
||||
|
|
||||
| empty(self)
|
||||
| Return True if the queue is empty, False otherwise (not reliable!).
|
||||
|
|
||||
| This method is likely to be removed at some point. Use qsize() == 0
|
||||
| as a direct substitute, but be aware that either approach risks a race
|
||||
| condition where a queue can grow before the result of empty() or
|
||||
| qsize() can be used.
|
||||
|
|
||||
| To create code that needs to wait for all queued tasks to be
|
||||
| completed, the preferred technique is to use the join() method.
|
||||
|
|
||||
| full(self)
|
||||
| Return True if the queue is full, False otherwise (not reliable!).
|
||||
|
|
||||
| This method is likely to be removed at some point. Use qsize() >= n
|
||||
| as a direct substitute, but be aware that either approach risks a race
|
||||
| condition where a queue can shrink before the result of full() or
|
||||
| qsize() can be used.
|
||||
|
|
||||
| get(self, block=True, timeout=None)
|
||||
| Remove and return an item from the queue.
|
||||
|
|
||||
| If optional args 'block' is true and 'timeout' is None (the default),
|
||||
| block if necessary until an item is available. If 'timeout' is
|
||||
| a positive number, it blocks at most 'timeout' seconds and raises
|
||||
| the Empty exception if no item was available within that time.
|
||||
| Otherwise ('block' is false), return an item if one is immediately
|
||||
| available, else raise the Empty exception ('timeout' is ignored
|
||||
| in that case).
|
||||
|
|
||||
| get_nowait(self)
|
||||
| Remove and return an item from the queue without blocking.
|
||||
|
|
||||
| Only get an item if one is immediately available. Otherwise
|
||||
| raise the Empty exception.
|
||||
|
|
||||
| join(self)
|
||||
| Blocks until all items in the Queue have been gotten and processed.
|
||||
|
|
||||
| The count of unfinished tasks goes up whenever an item is added to the
|
||||
| queue. The count goes down whenever a consumer thread calls task_done()
|
||||
| to indicate the item was retrieved and all work on it is complete.
|
||||
|
|
||||
| When the count of unfinished tasks drops to zero, join() unblocks.
|
||||
|
|
||||
| put(self, item, block=True, timeout=None)
|
||||
| Put an item into the queue.
|
||||
|
|
||||
| If optional args 'block' is true and 'timeout' is None (the default),
|
||||
| block if necessary until a free slot is available. If 'timeout' is
|
||||
| a positive number, it blocks at most 'timeout' seconds and raises
|
||||
| the Full exception if no free slot was available within that time.
|
||||
| Otherwise ('block' is false), put an item on the queue if a free slot
|
||||
| is immediately available, else raise the Full exception ('timeout'
|
||||
| is ignored in that case).
|
||||
|
|
||||
| put_nowait(self, item)
|
||||
| Put an item into the queue without blocking.
|
||||
|
|
||||
| Only enqueue the item if a free slot is immediately available.
|
||||
| Otherwise raise the Full exception.
|
||||
|
|
||||
| qsize(self)
|
||||
| Return the approximate size of the queue (not reliable!).
|
||||
|
|
||||
| task_done(self)
|
||||
| Indicate that a formerly enqueued task is complete.
|
||||
|
|
||||
| Used by Queue consumer threads. For each get() used to fetch a task,
|
||||
| a subsequent call to task_done() tells the queue that the processing
|
||||
| on the task is complete.
|
||||
|
|
||||
| If a join() is currently blocking, it will resume when all items
|
||||
| have been processed (meaning that a task_done() call was received
|
||||
| for every item that had been put() into the queue).
|
||||
|
|
||||
| Raises a ValueError if called more times than there were items
|
||||
| placed in the queue.
|
||||
|
|
||||
| ----------------------------------------------------------------------
|
||||
| Data descriptors inherited from Queue:
|
||||
|
|
||||
| __dict__
|
||||
| dictionary for instance variables (if defined)
|
||||
|
|
||||
| __weakref__
|
||||
| list of weak references to the object (if defined)
|
||||
|
||||
>>>
|
||||
13
Task/Priority-queue/Python/priority-queue-3.py
Normal file
13
Task/Priority-queue/Python/priority-queue-3.py
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
>>> from heapq import heappush, heappop, heapify
|
||||
>>> items = [(3, "Clear drains"), (4, "Feed cat"), (5, "Make tea"), (1, "Solve RC tasks"), (2, "Tax return")]
|
||||
>>> heapify(items)
|
||||
>>> while items:
|
||||
print(heappop(items))
|
||||
|
||||
|
||||
(1, 'Solve RC tasks')
|
||||
(2, 'Tax return')
|
||||
(3, 'Clear drains')
|
||||
(4, 'Feed cat')
|
||||
(5, 'Make tea')
|
||||
>>>
|
||||
89
Task/Priority-queue/Python/priority-queue-4.py
Normal file
89
Task/Priority-queue/Python/priority-queue-4.py
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
>>> help('heapq')
|
||||
Help on module heapq:
|
||||
|
||||
NAME
|
||||
heapq - Heap queue algorithm (a.k.a. priority queue).
|
||||
|
||||
DESCRIPTION
|
||||
Heaps are arrays for which a[k] <= a[2*k+1] and a[k] <= a[2*k+2] for
|
||||
all k, counting elements from 0. For the sake of comparison,
|
||||
non-existing elements are considered to be infinite. The interesting
|
||||
property of a heap is that a[0] is always its smallest element.
|
||||
|
||||
Usage:
|
||||
|
||||
heap = [] # creates an empty heap
|
||||
heappush(heap, item) # pushes a new item on the heap
|
||||
item = heappop(heap) # pops the smallest item from the heap
|
||||
item = heap[0] # smallest item on the heap without popping it
|
||||
heapify(x) # transforms list into a heap, in-place, in linear time
|
||||
item = heapreplace(heap, item) # pops and returns smallest item, and adds
|
||||
# new item; the heap size is unchanged
|
||||
|
||||
Our API differs from textbook heap algorithms as follows:
|
||||
|
||||
- We use 0-based indexing. This makes the relationship between the
|
||||
index for a node and the indexes for its children slightly less
|
||||
obvious, but is more suitable since Python uses 0-based indexing.
|
||||
|
||||
- Our heappop() method returns the smallest item, not the largest.
|
||||
|
||||
These two make it possible to view the heap as a regular Python list
|
||||
without surprises: heap[0] is the smallest item, and heap.sort()
|
||||
maintains the heap invariant!
|
||||
|
||||
FUNCTIONS
|
||||
heapify(...)
|
||||
Transform list into a heap, in-place, in O(len(heap)) time.
|
||||
|
||||
heappop(...)
|
||||
Pop the smallest item off the heap, maintaining the heap invariant.
|
||||
|
||||
heappush(...)
|
||||
Push item onto heap, maintaining the heap invariant.
|
||||
|
||||
heappushpop(...)
|
||||
Push item on the heap, then pop and return the smallest item
|
||||
from the heap. The combined action runs more efficiently than
|
||||
heappush() followed by a separate call to heappop().
|
||||
|
||||
heapreplace(...)
|
||||
Pop and return the current smallest value, and add the new item.
|
||||
|
||||
This is more efficient than heappop() followed by heappush(), and can be
|
||||
more appropriate when using a fixed-size heap. Note that the value
|
||||
returned may be larger than item! That constrains reasonable uses of
|
||||
this routine unless written as part of a conditional replacement:
|
||||
|
||||
if item > heap[0]:
|
||||
item = heapreplace(heap, item)
|
||||
|
||||
merge(*iterables)
|
||||
Merge multiple sorted inputs into a single sorted output.
|
||||
|
||||
Similar to sorted(itertools.chain(*iterables)) but returns a generator,
|
||||
does not pull the data into memory all at once, and assumes that each of
|
||||
the input streams is already sorted (smallest to largest).
|
||||
|
||||
>>> list(merge([1,3,5,7], [0,2,4,8], [5,10,15,20], [], [25]))
|
||||
[0, 1, 2, 3, 4, 5, 5, 7, 8, 10, 15, 20, 25]
|
||||
|
||||
nlargest(n, iterable, key=None)
|
||||
Find the n largest elements in a dataset.
|
||||
|
||||
Equivalent to: sorted(iterable, key=key, reverse=True)[:n]
|
||||
|
||||
nsmallest(n, iterable, key=None)
|
||||
Find the n smallest elements in a dataset.
|
||||
|
||||
Equivalent to: sorted(iterable, key=key)[:n]
|
||||
|
||||
DATA
|
||||
__about__ = 'Heap queues\n\n[explanation by François Pinard]\n\nH... t...
|
||||
__all__ = ['heappush', 'heappop', 'heapify', 'heapreplace', 'merge', '...
|
||||
|
||||
FILE
|
||||
c:\python32\lib\heapq.py
|
||||
|
||||
|
||||
>>>
|
||||
27
Task/Priority-queue/R/priority-queue-1.r
Normal file
27
Task/Priority-queue/R/priority-queue-1.r
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
PriorityQueue <- function() {
|
||||
keys <<- values <<- NULL
|
||||
insert <- function(key, value) {
|
||||
temp <- c(keys, key)
|
||||
ord <- order(temp)
|
||||
keys <<- temp[ord]
|
||||
values <<- c(values, list(value))[ord]
|
||||
}
|
||||
pop <- function() {
|
||||
head <- values[[1]]
|
||||
values <<- values[-1]
|
||||
keys <<- keys[-1]
|
||||
return(head)
|
||||
}
|
||||
empty <- function() length(keys) == 0
|
||||
list(insert = insert, pop = pop, empty = empty)
|
||||
}
|
||||
|
||||
pq <- PriorityQueue()
|
||||
pq$insert(3, "Clear drains")
|
||||
pq$insert(4, "Feed cat")
|
||||
pq$insert(5, "Make tea")
|
||||
pq$insert(1, "Solve RC tasks")
|
||||
pq$insert(2, "Tax return")
|
||||
while(!pq$empty()) {
|
||||
print(pq$pop())
|
||||
}
|
||||
5
Task/Priority-queue/R/priority-queue-2.r
Normal file
5
Task/Priority-queue/R/priority-queue-2.r
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
[1] "Solve RC tasks"
|
||||
[1] "Tax return"
|
||||
[1] "Clear drains"
|
||||
[1] "Feed cat"
|
||||
[1] "Make tea"
|
||||
18
Task/Priority-queue/R/priority-queue-3.r
Normal file
18
Task/Priority-queue/R/priority-queue-3.r
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
PriorityQueue <-
|
||||
setRefClass("PriorityQueue",
|
||||
fields = list(keys = "numeric", values = "list"),
|
||||
methods = list(
|
||||
insert = function(key,value) {
|
||||
temp <- c(keys,key)
|
||||
ord <- order(temp)
|
||||
keys <<- temp[ord]
|
||||
values <<- c(values,list(value))[ord]
|
||||
},
|
||||
pop = function() {
|
||||
head <- values[[1]]
|
||||
keys <<- keys[-1]
|
||||
values <<- values[-1]
|
||||
return(head)
|
||||
},
|
||||
empty = function() length(keys) == 0
|
||||
))
|
||||
1
Task/Priority-queue/R/priority-queue-4.r
Normal file
1
Task/Priority-queue/R/priority-queue-4.r
Normal file
|
|
@ -0,0 +1 @@
|
|||
pq <- PriorityQueue$new()
|
||||
51
Task/Priority-queue/Ruby/priority-queue.rb
Normal file
51
Task/Priority-queue/Ruby/priority-queue.rb
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
class PriorityQueueNaive
|
||||
def initialize
|
||||
@q = Hash.new { |h, k| h[k] = []}
|
||||
@priorities = []
|
||||
end
|
||||
|
||||
def push(priority, item)
|
||||
@q[priority] << item
|
||||
@priorities = @q.keys.sort
|
||||
end
|
||||
|
||||
def pop
|
||||
p = @priorities[0]
|
||||
item = @q[p].shift
|
||||
if @q[p].empty?
|
||||
@q.delete(p)
|
||||
@priorities.shift
|
||||
end
|
||||
item
|
||||
end
|
||||
|
||||
def peek
|
||||
if not empty?
|
||||
@q[@priorities[0]][0]
|
||||
end
|
||||
end
|
||||
|
||||
def empty?
|
||||
@priorities.empty?
|
||||
end
|
||||
|
||||
def inspect
|
||||
@q.inspect
|
||||
end
|
||||
end
|
||||
|
||||
test = [
|
||||
[6, "drink tea"],
|
||||
[3, "Clear drains"],
|
||||
[4, "Feed cat"],
|
||||
[5, "Make tea"],
|
||||
[6, "eat biscuit"],
|
||||
[1, "Solve RC tasks"],
|
||||
[2, "Tax return"],
|
||||
]
|
||||
|
||||
pq = PriorityQueueNaive.new
|
||||
test.each {|pr, str| pq.push(pr, str) }
|
||||
until pq.empty?
|
||||
puts pq.pop
|
||||
end
|
||||
45
Task/Priority-queue/Run-BASIC/priority-queue.run
Normal file
45
Task/Priority-queue/Run-BASIC/priority-queue.run
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
sqliteconnect #mem, ":memory:"
|
||||
#mem execute("CREATE TABLE queue (priority float,descr text)")
|
||||
|
||||
' --------------------------------------------------------------
|
||||
' Insert items into the que
|
||||
' --------------------------------------------------------------
|
||||
#mem execute("INSERT INTO queue VALUES (3,'Clear drains')")
|
||||
#mem execute("INSERT INTO queue VALUES (4,'Feed cat')")
|
||||
#mem execute("INSERT INTO queue VALUES (5,'Make tea')")
|
||||
#mem execute("INSERT INTO queue VALUES (1,'Solve RC tasks')")
|
||||
#mem execute("INSERT INTO queue VALUES (2,'Tax return')")
|
||||
|
||||
'--------------- insert priority between 4 and 5 -----------------
|
||||
#mem execute("INSERT INTO queue VALUES (4.5,'My Special Project')")
|
||||
|
||||
what$ = " -------------- Find first priority ---------------------"
|
||||
mem$ = "SELECT * FROM queue ORDER BY priority LIMIT 1"
|
||||
gosub [getQueue]
|
||||
|
||||
what$ = " -------------- Find last priority ---------------------"
|
||||
mem$ = "SELECT * FROM queue ORDER BY priority desc LIMIT 1"
|
||||
gosub [getQueue]
|
||||
|
||||
what$ = " -------------- Delete Highest Priority ---------------------"
|
||||
mem$ = "DELETE FROM queue WHERE priority = (select max(q.priority) FROM queue as q)"
|
||||
#mem execute(mem$)
|
||||
|
||||
what$ = " -------------- List Priority Sequence ---------------------"
|
||||
mem$ = "SELECT * FROM queue ORDER BY priority"
|
||||
gosub [getQueue]
|
||||
end
|
||||
|
||||
|
||||
[getQueue]
|
||||
print what$
|
||||
#mem execute(mem$)
|
||||
rows = #mem ROWCOUNT()
|
||||
print "Priority Description"
|
||||
for i = 1 to rows
|
||||
#row = #mem #nextrow()
|
||||
priority = #row priority()
|
||||
descr$ = #row descr$()
|
||||
print priority;" ";descr$
|
||||
next i
|
||||
RETURN
|
||||
9
Task/Priority-queue/Scala/priority-queue-1.scala
Normal file
9
Task/Priority-queue/Scala/priority-queue-1.scala
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
import scala.collection.mutable.PriorityQueue
|
||||
case class Task(prio:Int, text:String) extends Ordered[Task] {
|
||||
def compare(that: Task)=that.prio compare this.prio
|
||||
}
|
||||
|
||||
//test
|
||||
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)
|
||||
4
Task/Priority-queue/Scala/priority-queue-2.scala
Normal file
4
Task/Priority-queue/Scala/priority-queue-2.scala
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
case class Task(prio:Int, text:String)
|
||||
implicit def taskOrdering=new Ordering[Task] {
|
||||
def compare(t1:Task, t2:Task):Int=t2.prio compare t1.prio
|
||||
}
|
||||
29
Task/Priority-queue/Standard-ML/priority-queue.ml
Normal file
29
Task/Priority-queue/Standard-ML/priority-queue.ml
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
structure TaskPriority = struct
|
||||
type priority = int
|
||||
val compare = Int.compare
|
||||
type item = int * string
|
||||
val priority : item -> int = #1
|
||||
end
|
||||
|
||||
structure PQ = LeftPriorityQFn (TaskPriority)
|
||||
;
|
||||
|
||||
let
|
||||
val tasks = [
|
||||
(3, "Clear drains"),
|
||||
(4, "Feed cat"),
|
||||
(5, "Make tea"),
|
||||
(1, "Solve RC tasks"),
|
||||
(2, "Tax return")]
|
||||
val pq = foldr PQ.insert PQ.empty tasks
|
||||
(* or val pq = PQ.fromList tasks *)
|
||||
fun aux pq' =
|
||||
case PQ.next pq' of
|
||||
NONE => ()
|
||||
| SOME ((prio, name), pq'') => (
|
||||
print (Int.toString prio ^ ", " ^ name ^ "\n");
|
||||
aux pq''
|
||||
)
|
||||
in
|
||||
aux pq
|
||||
end
|
||||
18
Task/Priority-queue/Tcl/priority-queue.tcl
Normal file
18
Task/Priority-queue/Tcl/priority-queue.tcl
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
package require struct::prioqueue
|
||||
|
||||
set pq [struct::prioqueue]
|
||||
foreach {priority task} {
|
||||
3 "Clear drains"
|
||||
4 "Feed cat"
|
||||
5 "Make tea"
|
||||
1 "Solve RC tasks"
|
||||
2 "Tax return"
|
||||
} {
|
||||
# Insert into the priority queue
|
||||
$pq put $task $priority
|
||||
}
|
||||
# Drain the queue, in priority-sorted order
|
||||
while {[$pq size]} {
|
||||
# Remove the front-most item from the priority queue
|
||||
puts [$pq get]
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue