aboutsummaryrefslogtreecommitdiff
path: root/challenge-018/athanasius/perl5/MyPriorityQueue.pm
blob: d3c1d77f7f4ec543bf7ed2545a4f5768e2c26a62 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!perl

################################################################################
=comment

Perl Weekly Challenge 018
=========================

Task #2
-------
Write a script to implement *Priority Queue*. It is like regular *queue* except
each element has a *priority* associated with it. In a priority queue, an
element with high priority is served before an element with low priority. Please
check this [ https://en.wikipedia.org/wiki/Priority_queue |wiki page] for more
informations. It should serve the following operations:

  1) *is_empty*: check whether the queue has no elements.

  2) *insert_with_priority*: add an element to the queue with an associated
      priority.

  3) *pull_highest_priority_element*: remove the element from the queue that has
      the highest priority, and return it. If two elements have the same
      priority, then return element added first.

=cut
################################################################################

#--------------------------------------#
# Copyright © 2019 PerlMonk Athanasius #
#--------------------------------------#

package MyPriorityQueue;

use strict;
use warnings;
use List::Priority;

sub new
{
    my ($class, $reverse) = @_;

    my $self =
       {
           implementation   => List::Priority->new,
           reverse_priority => $reverse // 0,
       };

    return bless $self, $class;
}

sub is_empty
{
    my ($self) = @_;

    return $self->{implementation}->size == 0;
}

sub insert_with_priority
{
    my ($self, $priority, $scalar) = @_;

    my  $result = $self->{implementation}->insert($priority, $scalar);

    $result eq '1' or die $result;
}

sub pull_highest_priority_element
{
    my ($self) = @_;

    # If the queue is empty, undef will be returned

    return $self->{reverse_priority} ? $self->{implementation}->shift :
                                       $self->{implementation}->pop;
}

################################################################################
1;
################################################################################