diff options
| author | Jen <jen@southpawgeek.com> | 2020-03-01 23:08:23 -0500 |
|---|---|---|
| committer | Jen <jen@southpawgeek.com> | 2020-03-01 23:08:23 -0500 |
| commit | e28fd320ca245a7a312d520a6618e13597c50f94 (patch) | |
| tree | 9b724c266797dd0e14f2130f6a63c744e29c11c4 | |
| parent | a42746b136af9ddf5f0460f32a7fb49ba76783d4 (diff) | |
| download | perlweeklychallenge-club-e28fd320ca245a7a312d520a6618e13597c50f94.tar.gz perlweeklychallenge-club-e28fd320ca245a7a312d520a6618e13597c50f94.tar.bz2 perlweeklychallenge-club-e28fd320ca245a7a312d520a6618e13597c50f94.zip | |
cache solution, a bit late
| -rw-r--r-- | challenge-049/southpawgeek/ch-2.pl | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/challenge-049/southpawgeek/ch-2.pl b/challenge-049/southpawgeek/ch-2.pl new file mode 100644 index 0000000000..a1ee43cbb2 --- /dev/null +++ b/challenge-049/southpawgeek/ch-2.pl @@ -0,0 +1,70 @@ +#!/usr/bin/perl +use strict; +use warnings; +use feature qw/say/; + +my $cap = 3; +($cap) = @ARGV if @ARGV; +die "$cap isn't an int! \n" if $cap =~ /\D/; + +say "ok, capacity set to $cap"; + +my @keys; +my %cache; + +set(1,3); +set(2,5); +set(3,7); +say get(2), "\n"; +say get(1), "\n"; +say get(4), "\n"; +set(4,9); +say get(3), "\n"; +set(5,11); +say get(2), "\n"; + +sub set{ + my ($key, $val) = @_; + + # remove oldest element if we're full + if (scalar @keys >= $cap) { + my $discard = shift @keys if scalar @keys >= $cap; + say "discarded oldest cache data with key $discard"; + delete $cache{$discard}; + } + + # push returns number of elements, so subtract 1 + my $index = (push @keys, $key) - 1; + + # populate the cache + $cache{$key} = {'value' => $val, 'index' => $index}; + say "added $key, $val at index $index"; + + say "LRU @keys MRU\n"; +} + +sub get{ + my $key = shift; + say "getting value for key $key..."; + + my $val = $cache{$key}->{'value'} || undef; + say "$key isn't there" and return -1 unless $val; + + my $index = $cache{$key}->{'index'}; + say "found $key, $val at index $index"; + + my $removed = splice @keys, $index, 1; + say "removed $removed from index $index"; + + push @keys, $key; + + # this will be number of elements - 1 unless something has gone wrong + $index = scalar @keys - 1; + say "MRU key $key is now indexed at $index"; + + # also update the cache index + $cache{$key}->{'index'} = $index; + + say "LRU @keys MRU"; + return $val; +}
\ No newline at end of file |
