aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorMohammad S Anwar <Mohammad.Anwar@yahoo.com>2020-02-28 09:52:32 +0000
committerGitHub <noreply@github.com>2020-02-28 09:52:32 +0000
commit459d6a8a20c3ba37d3419e8b67ffab59c4ba1e7d (patch)
tree6174d051a2c457139f12c9ccaf8fddb6cc32f774
parent84efc21574cacae80bf4a83be6f5dd7862e5a025 (diff)
parent074809620ef3c7c0b136fcf031244126c90d0f44 (diff)
downloadperlweeklychallenge-club-459d6a8a20c3ba37d3419e8b67ffab59c4ba1e7d.tar.gz
perlweeklychallenge-club-459d6a8a20c3ba37d3419e8b67ffab59c4ba1e7d.tar.bz2
perlweeklychallenge-club-459d6a8a20c3ba37d3419e8b67ffab59c4ba1e7d.zip
Merge pull request #1321 from Doomtrain14/master
Added perl5 solution for ch#49-2
-rw-r--r--challenge-049/yet-ebreo/perl5/ch-2.pl80
1 files changed, 80 insertions, 0 deletions
diff --git a/challenge-049/yet-ebreo/perl5/ch-2.pl b/challenge-049/yet-ebreo/perl5/ch-2.pl
new file mode 100644
index 0000000000..7b8d1ade41
--- /dev/null
+++ b/challenge-049/yet-ebreo/perl5/ch-2.pl
@@ -0,0 +1,80 @@
+#!/usr/bin/perl
+
+use strict;
+use warnings;
+use feature 'say';
+
+my $cache = lru->new(3);
+$cache->set(1,3);
+$cache->set(2,5);
+$cache->set(3,7);
+say $cache->get(2);
+say $cache->get(1);
+say $cache->get(4);
+$cache->set(4,9);
+say $cache->get(3);
+
+package lru;
+sub new {
+
+ my $class = shift;
+ #Create a class/package that has
+ #Variable object to hold the cache size/capacity
+ #Hash object to hold key-value pairs
+ #Array object to hold the order of LRU (LRU ... MRU)
+ my $self = {
+ 'size' => shift,
+ 'hash' => {},
+ 'order' => []
+ };
+ bless $self, $class;
+ return $self;
+}
+
+sub set {
+ my ($self, $key, $value) = @_;
+
+ #Delete LRU from hash and update order if
+ #cache is FULL (hash size is equal to cache size)
+ if ((!exists ($self->{hash}{$key})) && (~~keys %{$self->{hash}} >= $self->{size})) {
+ delete $self->{hash}{$self->{order}[0]};
+ shift @{$self->{order}};
+ }
+
+ #Update order array
+ #If the key already exists in cache remove the key from order array then...
+ if (exists ($self->{hash}{$key})) {
+ @{$self->{order}} = grep { $_ != $key } @{$self->{order}};
+ }
+
+ #put it in last/highest index (Considered as MRU)
+ push @{$self->{order}}, $key;
+
+ #Update hash key-value pair
+ $self->{hash}{$key} = $value;
+}
+
+sub get {
+ my ($self, $key) = @_;
+
+ if (exists $self->{hash}{$key}) {
+ #Update the order of the array same as the one in Set method
+ @{$self->{order}} = grep { $_ != $key } @{$self->{order}};
+
+ #put it in last/highest index (Considered as MRU)
+ push @{$self->{order}}, $key;
+
+ #Return the value of the given key
+ return $self->{hash}{$key}
+ } else {
+ return -1;
+ }
+
+}
+=begin
+perl .\ch-2.pl
+5
+3
+-1
+-1
+=cut \ No newline at end of file