NOTE: I am trying to find the name of the specific LRU algorithm, not that this is a caching algorithm (I know it is, I wrote it). Telling me this is a caching algorithm is like telling someone looking for the name red-black tree that it is a tree balancing algorithm.
I recently created the following algorithm, but I am fairly certain someone must have done this before me and given it a name. Does this look familiar to anyone?
Purpose: Keep a fixed size pool of strings and the number of times they have been seen. If the pool exceeds the max size, only keep the most recently used items.
Pseudocode:
var cur
var old
func add_key(key)
if cur not defined
put a hash in cur
if key in old
copy value from old to cur for this key
delete key from old
increment cur[key]
if there are too many keys in cur
replace old with cur
empty cur
copy value from old to cur for this key
delete key from old
return cur[key]
A simple implementation in Perl 5 looks like:
#!/usr/bin/perl
use strict;
use warnings;
{ package Fixed::LRU::Counter;
sub new {
my ($class, $max) = @_;
return bless {
max => $max,
cur => {},
old => {},
}, $class;
}
sub add_key {
my ($self, $k) = @_;
if ($self->{old}{$k}) {
$self->{cur}{$k} = $self->{old}{$k};
delete $self->{old}{$k};
}
$self->{cur}{$k}++;
if (keys %{$self->{cur}} > $self->{max}) {
$self->{old} = $self->{cur};
$self->{cur} = { $k => $self->{old}{$k} };
delete $self->{old}{$k};
}
return $self->{cur}{$k};
}
}
my $c = Fixed::LRU::Counter->new(3);
for my $k (qw/a a b c d e f f g a f/) {
print "$k: ", $c->add_key($k), "\n";
}
Least frequently used cache algorithm
It is not LRU because LRU orders the cache items by last access time, not by access count like you do.