/* pagerep.c - page replacement: FIFO, LRU, Optimal (BACSE106 Lab 12) */
#include <stdio.h>

int main(void)
{
    int n, f, choice, i, j, k;
    int ref[50], frame[10], last[10], faults = 0, next = 0;

    printf("Length of reference string: ");
    scanf("%d", &n);
    printf("Reference string: ");
    for (i = 0; i < n; i++) scanf("%d", &ref[i]);
    printf("Number of frames: ");
    scanf("%d", &f);
    printf("1.FIFO  2.LRU  3.Optimal  Choice: ");
    scanf("%d", &choice);

    for (j = 0; j < f; j++) frame[j] = -1;              /* -1 = empty frame */

    printf("\nRef  Frames      Result\n");
    for (i = 0; i < n; i++) {
        int hit = -1;
        for (j = 0; j < f; j++)
            if (frame[j] == ref[i]) hit = j;

        if (hit != -1) {
            last[hit] = i;                              /* LRU: remember last use */
        } else {
            int victim = -1;
            for (j = 0; j < f; j++)                     /* use an empty frame first */
                if (frame[j] == -1) { victim = j; break; }
            if (victim == -1) {
                if (choice == 1) {                      /* FIFO: circular pointer */
                    victim = next;
                    next = (next + 1) % f;
                } else if (choice == 2) {               /* LRU: smallest last-use time */
                    victim = 0;
                    for (j = 1; j < f; j++)
                        if (last[j] < last[victim]) victim = j;
                } else {                                /* Optimal: used farthest in future */
                    int far = -1;
                    for (j = 0; j < f; j++) {
                        for (k = i + 1; k < n; k++)
                            if (ref[k] == frame[j]) break;
                        if (k > far) { far = k; victim = j; }   /* k == n means never used again */
                    }
                }
            } else if (choice == 1) {
                next = (victim + 1) % f;
            }
            frame[victim] = ref[i];
            last[victim] = i;
            faults++;
        }
        printf("%-4d ", ref[i]);
        for (j = 0; j < f; j++)
            if (frame[j] == -1) printf("-  "); else printf("%-2d ", frame[j]);
        printf("   %s\n", hit != -1 ? "Hit" : "Fault");
    }
    printf("\nTotal page faults = %d\nHit ratio = %.2f%%\n", faults, 100.0 * (n - faults) / n);
    return 0;
}
