Scala的LRU算法實現

/**
 * Created by Bruce on 2017/6/15.
 */

/**
 * Input:array = [1,2,3,5,8,4,5,2,9], size = 4
 * Output: result = 8
 * LRU分析參考:
 * ⑴get(key):如果key在cache中,則返回對應的value值,否則返回-1
 * ⑵set(key,value):如果key不在cache中,則將該(key,value)插入cache中
 * (注意,如果cache已滿,則必須把最近最久未使用的元素從cache中刪除);如果key在cache中,則重置value的值。
 * cacheQqueue  in     缺頁數
 * 1,2,3,5      8        4
 * 2,3,5,8      4        5
 * 3,5,8,4      5        6
 * 3,5,8,4      2        6
 * 5,8,4,2      9        7
 * 8,4,2,9               8
 *
 */
object page extends App{

  def lru(list:List[Int],q:Int):Int= {
    var count = 0  //統計缺頁數
    val listCache = scala.collection.mutable.ListBuffer[Int]()  //聲明一個可變list集合用作緩存
    for(a <- list){
      //如果緩存中不存在該元素,則將該元素放到緩存隊列中(如果list中的元素個數超過緩存大小,則移除list.head)
      if(!listCache.exists(c => c==a)){
        listCache += a
        count +=1
        if(listCache.length>=q)
          listCache-=listCache.head
      }
    }
    return count
  }

  println(lru(List(1,2,3,5,8,4,5,2,9),4))
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章