Write the simulation program for demand paging and show the page scheduling and total number of page faults according the LRU page replacement algorithm. Assume the memory of n frames.
Reference String :    8, 5, 7, 8, 5, 7, 2, 3, 7, 3, 5, 9, 4, 6, 2

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_FRAMES 100
#define MAX_REFERENCES 100

// Function to simulate LRU page replacement algorithm
void lru_page_replacement(int reference_string[], int num_references, int num_frames) {
    int frames[MAX_FRAMES];
    int page_faults = 0;
    int frame_count = 0;
    int page_positions[MAX_FRAMES];
    int current_time = 0;

    // Initialize all frames to -1 (indicating empty)
    for (int i = 0; i < num_frames; i++) {
        frames[i] = -1;
        page_positions[i] = -1;
    }

    printf("Reference String: ");
    for (int i = 0; i < num_references; i++) {
        printf("%d ", reference_string[i]);
    }
    printf("\n");

    printf("Page Scheduling:\n");

    for (int i = 0; i < num_references; i++) {
        int page = reference_string[i];
        int page_index = -1;
        int lru_index = -1;
        int lru_time = -1;

        // Check if the page is already in one of the frames
        for (int j = 0; j < num_frames; j++) {
            if (frames[j] == page) {
                page_index = j;
                break;
            }
        }

        if (page_index == -1) { // Page fault
            // Find the least recently used page
            for (int j = 0; j < num_frames; j++) {
                if (page_positions[j] < lru_time || lru_time == -1) {
                    lru_index = j;
                    lru_time = page_positions[j];
                }
            }

            // Replace the LRU page with the new page
            frames[lru_index] = page;
            page_positions[lru_index] = current_time;
            page_faults++;

            printf("Reference: %d | Frames: ", page);
            for (int j = 0; j < num_frames; j++) {
                printf("%d ", frames[j]);
            }
            printf("(Page fault)\n");
        } else {
            // Update the position of the page in the LRU tracker
            page_positions[page_index] = current_time;
            printf("Reference: %d | Frames: ", page);
            for (int j = 0; j < num_frames; j++) {
                printf("%d ", frames[j]);
            }
            printf("(No page fault)\n");
        }

        current_time++;
    }

    printf("Total Page Faults: %d\n", page_faults);
}

int main() {
    // Define the reference string and the number of frames
    int reference_string[] = {8, 5, 7, 8, 5, 7, 2, 3, 7, 3, 5, 9, 4, 6, 2};
    int num_references = sizeof(reference_string) / sizeof(reference_string[0]);
    int num_frames = 3; // Number of memory frames

    // Simulate LRU page replacement
    lru_page_replacement(reference_string, num_references, num_frames);

    return 0;
}