From 77fef6217389869a832b5b7b08fc147f7abf5610 Mon Sep 17 00:00:00 2001 From: TanmayMachkar Date: Sat, 12 Oct 2024 22:06:35 +0530 Subject: [PATCH] added b7 code --- ...e Replacement Algorithm - LRU, Optimal.cpp | 136 ++++++++++++++++++ 1 file changed, 136 insertions(+) create mode 100644 Codes/Group B/Assignment - 7/Page Replacement Algorithm - LRU, Optimal.cpp diff --git a/Codes/Group B/Assignment - 7/Page Replacement Algorithm - LRU, Optimal.cpp b/Codes/Group B/Assignment - 7/Page Replacement Algorithm - LRU, Optimal.cpp new file mode 100644 index 0000000..8908ca2 --- /dev/null +++ b/Codes/Group B/Assignment - 7/Page Replacement Algorithm - LRU, Optimal.cpp @@ -0,0 +1,136 @@ +#include +using namespace std; + +int refstring[] = {0, 2, 1, 6, 4, 0, 1, 0, 3, 1, 2, 1}; +int win, hit = 0, miss = 0, res[4], lastUsed[40]; + +int findLRU() { + int minIndex = 0; + for(int i = 1; i < win; i++){ + if(lastUsed[i] < lastUsed[minIndex]){ + minIndex = i; + } + } + return minIndex; +} + +void lru(int rf[], int len) +{ + for(int i = 0; i < win; i++) { + res[i] = -1; + lastUsed[i] = -1; + } + + for(int j = 0; j < len; j++) { + bool hitFlag = false; + for(int k = 0; k < win; k++){ + if (res[k] == rf[j]){ + hit++; + lastUsed[k] = j; + hitFlag = true; + break; + } + } + if (!hitFlag) { + miss++; + bool emptyFound = false; + for(int k = 0; k < win; k++){ + if (res[k] == -1){ + res[k] = rf[j]; + lastUsed[k] = j; + emptyFound = true; + break; + } + } + if(!emptyFound){ + int lruIndex = findLRU(); + res[lruIndex] = rf[j]; + lastUsed[lruIndex] = j; + } + } + } + + cout<<"\nNo of hits (LRU): "< farthest){ + farthest = j; + maxIndex = i; + } + break; + } + } + if(j == len) + return i; + } + return maxIndex; +} + +void optimal(int rf[], int len){ + hit = 0; + miss = 0; + + for(int i = 0; i < win; i++){ + res[i] = -1; + } + + for(int j = 0; j < len; j++){ + bool hitFlag = false; + for(int k = 0; k < win; k++){ + if (res[k] == rf[j]){ + hit++; + hitFlag = true; + break; + } + } + if (!hitFlag){ + miss++; + bool emptyFound = false; + for(int k = 0; k < win; k++){ + if (res[k] == -1){ + res[k] = rf[j]; + emptyFound = true; + break; + } + } + if(!emptyFound){ + int optimalIndex = findOptimal(rf, len, j); + res[optimalIndex] = rf[j]; + } + } + } + + cout<<"\nNo of hits (Optimal): "<>win; + int len = sizeof(refstring)/sizeof(refstring[0]); + + cout<<"\nBy LRU algorithm: "; + lru(refstring, len); + display(); + + cout<<"\n\nBy Optimal Algorithm: "; + optimal(refstring, len); + display(); +}