3
1
SystemsProgrammingAndOperat.../Codes/Group B/Code-B7.cpp

136 lines
2.8 KiB
C++
Raw Permalink Normal View History

// Assignment-B7 - Page Replacement in C++ (LRU + Optimal)
// BEGINNING OF CODE
#include <cmath>
#include <complex>
#include <iostream>
2024-10-12 22:06:35 +05:30
using namespace std;
int refString[] = {0, 2, 1, 6, 4, 0, 1, 0, 3, 1, 2, 1};
int window = 0, hit = 0, miss = 0, currentPages[4], lastUsed[40];
int len = sizeof(refString) / sizeof(refString[0]);
2024-10-12 22:06:35 +05:30
int findLRU() {
int min_index = 0;
for (int i=1; i<window; i++) {
if (lastUsed[i] < lastUsed[min_index]) {
min_index = i;
2024-10-12 22:06:35 +05:30
}
}
return min_index;
2024-10-12 22:06:35 +05:30
}
void LRU() {
for (int i=0; i<window; i++) {
currentPages[i] = -1;
lastUsed[i] = -1;
}
2024-10-12 22:06:35 +05:30
for (int i=0; i<len; i++) {
bool hitFlag = false;
for (int j=0; j<window; j++) {
if (currentPages[j] == refString[i]) {
hit++;
hitFlag = true;
lastUsed[j] = i;
break;
}
}
if (hitFlag == false) {
miss++;
bool emptyFound = false;
for (int j=0; j<window; j++) {
if (currentPages[j] == -1) {
emptyFound = true;
currentPages[j] = refString[i];
lastUsed[j] = i;
break;
2024-10-12 22:06:35 +05:30
}
}
if (emptyFound == false) {
int lru_index = findLRU();
currentPages[lru_index] = refString[i];
lastUsed[lru_index] = i;
2024-10-12 22:06:35 +05:30
}
}
}
cout<<endl<<"----- LRU ------";
cout<<endl<<"Number of hits: "<<hit;
cout<<endl<<"Number of misses: "<<miss;
2024-10-12 22:06:35 +05:30
}
int findOptimal(int current_index) {
int max_index = -1, farthest = current_index;
for (int i=0; i<window; i++) {
int j;
for (j=current_index+1; j<len; j++) {
if (currentPages[i] == refString[j]) {
if (j > farthest) {
farthest = j;
max_index = i;
2024-10-12 22:06:35 +05:30
}
break;
}
}
if (j == len) {
return i;
2024-10-12 22:06:35 +05:30
}
}
return max_index;
2024-10-12 22:06:35 +05:30
}
void Optimal() {
hit = 0;
miss = 0;
2024-10-12 22:06:35 +05:30
for (int i=0; i<window; i++) {
currentPages[i] = -1;
}
2024-10-12 22:06:35 +05:30
for (int i=0; i<len; i++) {
bool hitFlag = false;
for (int j=0; j<window; j++) {
if (currentPages[j] == refString[i]) {
hit++;
hitFlag = true;
break;
}
}
if (hitFlag == false) {
miss++;
bool emptyFound = false;
for (int j=0; j<window; j++) {
if (currentPages[j] == -1) {
emptyFound = true;
currentPages[j] = refString[i];
break;
2024-10-12 22:06:35 +05:30
}
}
if (emptyFound == false) {
int optimal_index = findOptimal(i);
currentPages[optimal_index] = refString[i];
}
2024-10-12 22:06:35 +05:30
}
}
cout<<endl<<"----- OPTIMAL -----";
cout<<endl<<"Number of hits: "<<hit;
cout<<endl<<"Number of misses: "<<miss;
2024-10-12 22:06:35 +05:30
}
void display() {
cout<<endl<<"Current pages are:\t";
for (int i=0; i<window; i++) {
cout<<currentPages[i]<<" ";
}
cout<<endl;
2024-10-12 22:06:35 +05:30
}
int main() {
cout<<endl<<"Enter window size:\t";
cin>>window;
LRU();
display();
Optimal();
display();
2024-10-12 22:06:35 +05:30
}
// END OF CODE