aboutsummaryrefslogtreecommitdiff
path: root/challenge-018
diff options
context:
space:
mode:
authorMartin Barth <ufobat@users.noreply.github.com>2019-07-27 14:46:26 +0200
committerGitHub <noreply@github.com>2019-07-27 14:46:26 +0200
commitb64516a94c5149f3d4af2073ff10321f2d5db6cb (patch)
tree840a7729bbe359c28c392a5a07a8974be8e52abd /challenge-018
parentd36ac05a5657658cf651024ac91f3d707ec0e41f (diff)
downloadperlweeklychallenge-club-b64516a94c5149f3d4af2073ff10321f2d5db6cb.tar.gz
perlweeklychallenge-club-b64516a94c5149f3d4af2073ff10321f2d5db6cb.tar.bz2
perlweeklychallenge-club-b64516a94c5149f3d4af2073ff10321f2d5db6cb.zip
Create priority-queue.pl6
Diffstat (limited to 'challenge-018')
-rw-r--r--challenge-018/martin-barth/priority-queue.pl641
1 files changed, 41 insertions, 0 deletions
diff --git a/challenge-018/martin-barth/priority-queue.pl6 b/challenge-018/martin-barth/priority-queue.pl6
new file mode 100644
index 0000000000..ca50cd29a2
--- /dev/null
+++ b/challenge-018/martin-barth/priority-queue.pl6
@@ -0,0 +1,41 @@
+class PriorityQueue {
+ class Item {
+ has Real $.prio;
+ has Any $.element;
+ }
+ has @.elements;
+
+ method insert-with-priority(Real:D $prio, Any:D $element) {
+ my $item = Item.new(:$prio, :$element);
+ my $new_pos = self!find-pos($prio, 0, @!elements.elems);
+ @!elements.splice($new_pos, 0, $item);
+ }
+
+ method !find-pos($prio, Int $start, Int $end) {
+ my $pos = (($start + $end) / 2);
+ if $pos < 0 {
+ return 0;
+ } else {
+ if $start == $end {
+ return $start;
+ } else {
+ $pos = $pos.Int;
+ my $item = @!elements[$pos];
+ if $item.prio < $prio {
+ return self!find-pos($prio, $start, $pos);
+ } else {
+ return self!find-pos($prio, $pos+1, $end);
+ }
+ }
+ }
+ }
+
+ method is-empty(--> Bool) {
+ return @!elements.elems == 0;
+ }
+
+ method pull-highest-priority-element(--> Any) {
+ fail if self.is-empty;
+ return @!elements.shift.element;
+ }
+}