diff options
| author | Mohammad S Anwar <Mohammad.Anwar@yahoo.com> | 2019-07-27 14:07:19 +0100 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2019-07-27 14:07:19 +0100 |
| commit | f91d157b8ce4e0d5b3b2fccdf70b54065a82cdc3 (patch) | |
| tree | 7ef0bb131caddc92cd2b6c76a003e6099bfd7513 /challenge-018 | |
| parent | fd3b7ecba8e74a27bde5fd2d7d3c319bc429241f (diff) | |
| parent | 9595daace67435a9d22731ca0841e00379b00030 (diff) | |
| download | perlweeklychallenge-club-f91d157b8ce4e0d5b3b2fccdf70b54065a82cdc3.tar.gz perlweeklychallenge-club-f91d157b8ce4e0d5b3b2fccdf70b54065a82cdc3.tar.bz2 perlweeklychallenge-club-f91d157b8ce4e0d5b3b2fccdf70b54065a82cdc3.zip | |
Merge pull request #424 from ufobat/patch-1
Create priority-queue.pl6
Diffstat (limited to 'challenge-018')
| -rw-r--r-- | challenge-018/martin-barth/perl6/ch-2.p6 | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/challenge-018/martin-barth/perl6/ch-2.p6 b/challenge-018/martin-barth/perl6/ch-2.p6 new file mode 100644 index 0000000000..ca50cd29a2 --- /dev/null +++ b/challenge-018/martin-barth/perl6/ch-2.p6 @@ -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; + } +} |
