Sure! Below is a simple C program that demonstrates the Optimal Page Replacement algorithm:
```c
#include <stdio.h>
#include <stdbool.h>
#define FRAME_SIZE 3 // Change this value for a different frame size
int findOptimal(int pages[], int n, int frame[], int frameSize, int startIndex) {
int res = -1, farthest = startIndex;
for (int i = 0; i < frameSize; i++) {
int j;
for (j = startIndex; j < n; j++) {
if (frame[i] == pages[j]) {
if (j > farthest) {
farthest = j;
res = i;
}
break;
}
}
if (j == n)
return i;
}
return (res == -1) ? 0 : res;
}
void optimalPageReplacement(int pages[], int n) {
int frame[FRAME_SIZE];
bool isPresent[FRAME_SIZE];
int pageFaults = 0;
for (int i = 0; i < FRAME_SIZE; i++) {
frame[i] = -1;
isPresent[i] = false;
}
for (int i = 0; i < n; i++) {
int page = pages[i];
if (!isPresent[page]) {
int replaceIndex = findOptimal(pages, n, frame, FRAME_SIZE, i + 1);
frame[replaceIndex] = page;
isPresent[replaceIndex] = true;
pageFaults++;
}
printf("\nPage %d -> Frames: ", page);
for (int j = 0; j < FRAME_SIZE; j++) {
if (frame[j] == -1)
printf("_ ");
else
printf("%d ", frame[j]);
}
}
printf("\nTotal Page Faults: %d\n", pageFaults);
}
int main() {
int pages[] = {1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5};
int n = sizeof(pages) / sizeof(pages[0]);
printf("Optimal Page Replacement Algorithm:\n");
optimalPageReplacement(pages, n);
return 0;
}
```
This program simulates the Optimal Page Replacement algorithm with a fixed frame size of 3 and uses a sample page reference string for demonstration purposes. You can modify the `FRAME_SIZE` constant and the `pages` array to test with different frame sizes and page reference strings.
Nilesh Raut Changed status to publish