diff options
| author | Ysmael Ebreo <Ysmael.Ebreo@latticesemi.com> | 2020-02-28 17:46:23 +0800 |
|---|---|---|
| committer | Ysmael Ebreo <Ysmael.Ebreo@latticesemi.com> | 2020-02-28 17:46:23 +0800 |
| commit | 074809620ef3c7c0b136fcf031244126c90d0f44 (patch) | |
| tree | 1bb5f3d6b259a208a07016c2514531d5abde29e7 | |
| parent | cdb0b83f9e5a7b5d390d3434928a9995bdf3441a (diff) | |
| download | perlweeklychallenge-club-074809620ef3c7c0b136fcf031244126c90d0f44.tar.gz perlweeklychallenge-club-074809620ef3c7c0b136fcf031244126c90d0f44.tar.bz2 perlweeklychallenge-club-074809620ef3c7c0b136fcf031244126c90d0f44.zip | |
Added perl5 solution for ch#49-2
| -rw-r--r-- | challenge-049/yet-ebreo/perl5/ch-2.pl | 80 |
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 |
