diff options
| author | Simon Proctor <simon.proctor@zpg.co.uk> | 2019-07-22 14:05:50 +0100 |
|---|---|---|
| committer | Simon Proctor <simon.proctor@zpg.co.uk> | 2019-07-22 14:05:50 +0100 |
| commit | 1d03bfdae1130bbf391661bbb7e3f6fd1917e6c3 (patch) | |
| tree | a269baa1553069b576e869e0a9bb4e7d3a506561 | |
| parent | ad5afaa24f905945daec75e9ebcb311d883436f7 (diff) | |
| download | perlweeklychallenge-club-1d03bfdae1130bbf391661bbb7e3f6fd1917e6c3.tar.gz perlweeklychallenge-club-1d03bfdae1130bbf391661bbb7e3f6fd1917e6c3.tar.bz2 perlweeklychallenge-club-1d03bfdae1130bbf391661bbb7e3f6fd1917e6c3.zip | |
Initial version of the queue
| -rw-r--r-- | challenge-018/simon-proctor/perl6/ch-2.p6 | 68 | ||||
| -rw-r--r-- | challenge-018/simon-proctor/perl6/test.csv | 9 |
2 files changed, 77 insertions, 0 deletions
diff --git a/challenge-018/simon-proctor/perl6/ch-2.p6 b/challenge-018/simon-proctor/perl6/ch-2.p6 new file mode 100644 index 0000000000..79c7161676 --- /dev/null +++ b/challenge-018/simon-proctor/perl6/ch-2.p6 @@ -0,0 +1,68 @@ +#!/usr/bin/env perl6 + +role SingleQueue { + has @!items; + + method add-item( $item ) { + @!items.push( $item ); + } + + method get-item() { + return @!items.shift; + } + + method is-empty() { + @!items.elems == 0; + } +} + +role OrderedQueue { + + has SingleQueue %!queues; + + method is_empty() { + self.is-empty(); + } + + method is-empty() { + [&&] %!queues.kv.map( -> $k, $v { $v.is-empty } ); + } + + method insert_with_priority( $item, Int() $priority ) { + self.insert-with-priority( $item, $priority ); + } + + method insert-with-priority( $item, Int() $priority ) { + %!queues{$priority} //= SingleQueue.new(); + %!queues{$priority}.add-item( $item ); + } + + method pull_highest_priority_element() { + self.pull-highest-priority-element() + } + + method pull-highest-priority-element() { + return Nil if self.is-empty; + my $queue = %!queues.keys.sort( {$^b <=> $^a }).first; + my $value = %!queues{$queue}.get-item; + if %!queues{$queue}.is-empty { + %!queues{$queue}:delete; + } + return $value; + } +} + +#| Given a file in csv format "priority,item" add all the items to the queue +#| then print them in the given order +sub MAIN( $file ) { + my $queue = OrderedQueue.new(); + + for $file.IO.lines -> $line { + my ( $priority, $item ) = $line.split(","); + $queue.insert-with-priority( $item, $priority ); + } + + while ! $queue.is-empty { + $queue.pull-highest-priority-element().say; + } +}
\ No newline at end of file diff --git a/challenge-018/simon-proctor/perl6/test.csv b/challenge-018/simon-proctor/perl6/test.csv new file mode 100644 index 0000000000..06209ce75b --- /dev/null +++ b/challenge-018/simon-proctor/perl6/test.csv @@ -0,0 +1,9 @@ +1,Apple +1,Pear +1,Orange +10,Carrot +9,Lettuce +1,Antelope +7,Seven +10,Another ten +11,Top Priority
\ No newline at end of file |
