From 6e475c2d984d2396ed72b73919d0e03e8aca8e09 Mon Sep 17 00:00:00 2001 From: Jaime <42359730+bracteatus@users.noreply.github.com> Date: Sat, 27 Jul 2019 17:16:50 -0600 Subject: Update ch-2.pl Snappy implementation of priority queue. --- challenge-018/jaime/perl5/ch-2.pl | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/challenge-018/jaime/perl5/ch-2.pl b/challenge-018/jaime/perl5/ch-2.pl index 10dce92536..d4ddde212e 100644 --- a/challenge-018/jaime/perl5/ch-2.pl +++ b/challenge-018/jaime/perl5/ch-2.pl @@ -14,3 +14,21 @@ # 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. + +my $queue = {}; + +sub is_empty { + return not map { @{$_} } values $queue; +} + +sub insert_with_priority { + my ($priority,$body) = @_; + $queue->{$priority} = [] unless $queue->{$priority}; + push @{$queue->{$priority}}, $body; +} + +sub pull_highest_priority_element { + for my $priority (reverse sort keys %$queue) { + return shift @{$queue->{$priority}} if @{$queue->{$priority}}; + } +} -- cgit