美文网首页
LFU算法的PHP实现

LFU算法的PHP实现

作者: 似水牛年 | 来源:发表于2019-04-03 22:22 被阅读0次
    /**
     * LFU是最近最不常用页面置换算法(Least Frequently Used),也就是淘汰一定时期内被访问次数最少的页
     */
    class LFU_Cache{
        private $array_lfu = array();
        private $array_count = array();
        private $max_size = 0;
    
        function __construct($size)
        {
            // 缓存最大存储
            $this->max_size = $size;
        }
    
        public function set_value($key, $value)
        {
            // 如果存在,则存入值
            if (array_key_exists($key, $this->array_lfu)) {
                $this->array_lfu[$key] = $value;
            }else if(count($this->array_lfu) < $this->max_size){
                $this->array_lfu[$key] = $value;
            }else{
                // 找出最少使用的key,删除它
                $min_key = '';
                $min_count = PHP_INT_MAX;
                foreach($this->array_count as $key=>$value){
                    if($value < $min_count){
                        $min_key = $key;
                        $min_count = $value;
                    }
                }
    
                unset($this->array_lfu[$min_key]);
                unset($this->array_count[$min_key]);
            }
    
            // 次数加一
            if (array_key_exists($key, $this->array_count)) {
                $this->array_count[$key] = $this->array_count[$key] + 1;
            }else{
                $this->array_count[$key] = 1;
            }
            
        }
    
        public function get_value($key)
        {
            $ret_value = false;
    
            if (array_key_exists($key, $this->array_lfu)) {
                $ret_value = $this->array_lfu[$key];
                $this->array_count[$key] = $this->array_count[$key] + 1;
            }
            return $ret_value;
        }
    
        public function vardump_cache()
        {
            var_dump($this->array_lfu);
        }
    }
    
    $cache = new LFU_Cache(5);
    $cache->set_value("01", "01");
    $cache->get_value('01');
    $cache->set_value("02", "02");
    $cache->set_value("03", "03");
    $cache->set_value("04", "04");
    $cache->set_value("05", "05");
    $cache->set_value("03", "33");
    $cache->vardump_cache();
    
    $cache->set_value("06", "06");
    $cache->set_value("07", "07");
    $cache->vardump_cache();
    

    相关文章

      网友评论

          本文标题:LFU算法的PHP实现

          本文链接:https://www.haomeiwen.com/subject/kxntiqtx.html