Optimal Page Replacement Algorithm Program Code in C++ .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
#include <bits/stdc++.h> using namespace std; const int N=100005; int n; int frame_size; int pages[N]; void optimal_page_replacement() { vector<int> fr; int page_faults = 0; for (int i = 0; i < n; i++) { int k; for (k = 0; k < fr.size(); k++) if (fr[k] == pages[i]) break; if (k==fr.size()) { if (fr.size() < frame_size) fr.push_back(pages[i]); else { int index=i+1; int res = -1, farthest = index; for (int l = 0; l < fr.size(); l++) { int j; for (j = index; j < n; j++) { if (fr[l] == pages[j]) { if (j > farthest) { farthest = j; res = l; } break; } } if (j == n) { res=l; break; } } fr[res] = pages[i]; } page_faults++; cout<<"Reference to page "<<pages[i]<<" caused a page fault\n"; } else { cout<<"Reference to page "<<pages[i]<<" did not cause a page fault\n"; } } cout<<"\nTotal Page Faults: "<<page_faults; } int main() { cout<<"Number of Frames: "; cin>>frame_size; cout<<"Page Reference Stream Length: "; cin>>n; cout<<"Page Reference Stream:\n"; for(int i=0; i<n; i++) cin>>pages[i]; optimal_page_replacement(); return 0; } |