LRU算法:商品浏览历史排序

来源:互联网 发布:软件研发部组织结构图 编辑:程序博客网 时间:2024/05/01 18:06


// id字符串 :  使用LRU算法

// 原有的cookie中的id            当前新访问的书的id  应该写回的id bookHistory的取值
// a.  cookie[] cs为null         11
// b.  没有bookHistory中的cookie       1         1
// c.  1 2 2-1
// d.  2-1 1 1-2
// e.  1-2 3 3-1-2
// f.  1-2-3 22-1-3
// g.  2-1-3 44-2-1
public String makeIds(HttpServletRequest request, String id) {
           // a 
           Cookie cs[] = request.getCookies();
           if(cs==null)
                     return id;
           // b(cs不为空)
          Cookie cookie = null;
          for(Cookie c : cs){
                   if(Constants.BOOK_HISTORY.equals(c.getName())){  
                              cookie = c;
                              break;
                   }
           }
                        
           if(cookie == null)
                   return id;
                        
           // cdefg
           String ids[] = cookie.getValue().split("\\-");
           LinkedList<String> list = new LinkedList<String>(Arrays.asList(ids));  // [1,2,3]
           // cde   
           if(list.size() < 3){
                  if(list.contains(id)){
                         list.remove(id);
                  }
                  list.addFirst(id);
            }else{ 
                  // fg 
                  if(list.contains(id)){
                          list.remove(id);
                  }else{
                          list.removeLast();
                  }
                   list.addFirst(id);
            }
                        
            StringBuffer sb = new StringBuffer();
            for(int i=0; i<list.size(); i++){
                   if(i>0)
                         sb.append("-");
                   sb.append(list.get(i));
            }
                        
            return sb.toString();

}

             







0 0