Reference String : 3, 5, 7, 2, 5, 1, 2, 3, 1, 3, 5, 3, 1, 6, 2
#include <stdio.h>
#include <stdlib.h>
#define MAX_FRAMES 100
#define REFERENCE_STRING_LENGTH 15
// Function to print the current state of frames
void printFrames(int frames[], int frame_count) {
for (int i = 0; i < frame_count; i++) {
if (frames[i] != -1)
printf("%d ", frames[i]);
else
printf("X ");
}
printf("\n");
}
// Function to find the index of the page that will not be used for the longest period of time
int findOptimalIndex(int frames[], int frame_count, int reference_string[], int current_index, int ref_len) {
int farthest = current_index;
int replace_index = -1;
for (int i = 0; i < frame_count; i++) {
int j;
for (j = current_index + 1; j < ref_len; j++) {
if (frames[i] == reference_string[j]) {
if (j > farthest) {
farthest = j;
replace_index = i;
}
break;
}
}
if (j == ref_len) {
return i; // If the page is not found in future references, replace it
}
}
return replace_index;
}
// Function to simulate Optimal Page Replacement
void optimalPageReplacement(int reference_string[], int ref_len, int frame_count) {
int frames[MAX_FRAMES];
int page_faults = 0;
// Initialize frames
for (int i = 0; i < frame_count; i++) {
frames[i] = -1;
}
for (int i = 0; i < ref_len; i++) {
int page = reference_string[i];
// Check if the page is already in frames
int found = 0;
for (int j = 0; j < frame_count; j++) {
if (frames[j] == page) {
found = 1;
break;
}
}
if (!found) {
// Page fault occurred
page_faults++;
int replace_index = findOptimalIndex(frames, frame_count, reference_string, i, ref_len);
frames[replace_index] = page;
}
// Print current state of frames
printFrames(frames, frame_count);
}
printf("Total number of page faults: %d\n", page_faults);
}
int main() {
int reference_string[REFERENCE_STRING_LENGTH] = {3, 5, 7, 2, 5, 1, 2, 3, 1, 3, 5, 3, 1, 6, 2};
int frame_count;
printf("Enter the number of frames: ");
scanf("%d", &frame_count);
if (frame_count > MAX_FRAMES || frame_count <= 0) {
printf("Invalid number of frames. Must be between 1 and %d.\n", MAX_FRAMES);
return 1;
}
optimalPageReplacement(reference_string, REFERENCE_STRING_LENGTH, frame_count);
return 0;
}
0 Comments