最近最少使用(LRU)演算法類比--LeastRecentPage

來源:互聯網
上載者:User
題目

最近最少使用(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;}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.