題目
最近最少使用(LRU)緩衝演算法從緩衝中收回最近最少使用元素(當緩衝滿時)。當緩衝請求元素後,應將元素添加到緩衝(如果之前不再緩衝中),並將其作為緩衝中最近使用最多的元素。 給快取的最大容量和一個整數(向緩衝發出請求),請使用LRU快取演算法計算快取請求失敗的次數。當請求的整數不在快取中時,說明快取請求失敗。
初始狀態下告訴緩衝是空的。
編寫程式類比LRU的運行過程,
依次輸入分配給某進程的緩衝大小(頁幀數)和該進程訪問頁面的次序,用-1作為輸入結束標誌,
初始時緩衝為空白,要求輸出使用LRU演算法的缺頁次數
測試案例 TestCase 1:
Input:
4
4 3 2 1 4 3 5 4 3 2 1 5 4 -1
Expected Return Value:
9
TestCase 2:
Input:
3
1 2 3 3 2 1 4 3 2 1 -1
Expected Return Value:
7
TestCase 3:
3
Input:
3 0 1 2 0 3 0 4 2 3 0 3 2 1 2 0 -1
Expected Return Value:
11
TestCase 4:
2
Input:
2 3 1 3 2 1 4 3 2-1
Expected Return Value:
8
代碼
import java.util.Scanner;public class LeastRecentPage {public static final int MAX_TASK_NUM = 100;public static void main(String[] args) {// TODO Auto-generated method stubScanner scan = new Scanner(System.in);while (scan.hasNext()) {int cacheBlocks = scan.nextInt();int[] taskPages = new int[MAX_TASK_NUM];int i = 0;int page = scan.nextInt();while (page != -1) // 輸入結束標誌{taskPages[i++] = page;page = scan.nextInt();}System.out.println(LRU.calMissingPages(cacheBlocks, i, taskPages));}scan.close();}}class LRU {public static int calMissingPages(int cacheBlocks, int taskNum, int taskPages[]) {int[] cache = new int[cacheBlocks]; // 緩衝cache[0] = taskPages[0]; // 預先處理,先將第一個作業頁面放入緩衝int cachePages = 1; // 已緩衝的頁面數int missingNum = 1; // 缺頁次數boolean missingFlag;// 缺頁標誌for (int i = 1; i < taskNum; i++) {missingFlag = true;for (int j = 0; j < cachePages; j++) {if (cache[j] == taskPages[i]) // 命中{missingFlag = false;int t = cache[j];// 插入排序將當前命中的元素移到隊尾for (int k = j + 1; k < cachePages; k++)cache[k - 1] = cache[k];cache[cachePages - 1] = t;break;}}if (missingFlag)// 未命中{missingNum++;if (cachePages == cacheBlocks) // 緩衝已滿{for (int k = 1; k < cachePages; k++)cache[k - 1] = cache[k];cache[cachePages - 1] = taskPages[i];} else // 緩衝未滿{cache[cachePages] = taskPages[i];cachePages++;}}}return missingNum;}