Optimal Page Replacement (OPT) in C

Exploring Optimal Page Replacement Algorithm in C

TheLazyBusyCoder's Blog

Welcome to my coding adventures! In this post, we'll explore a C program.

Optimal Page Replacement(OPT) in C

Check out YouTube video explaining theory: Watch now

        
#include <stdio.h>

int find(int frame[], int frameSize , int cur) {
	int i;
	for(i = 0; i < frameSize; i++) {
		if(cur == frame[i]) return 1;
	}
	return 0;
}

void display(int frame[] , int framesize , int hit) {
	int i;
	for(i = 0; i < framesize; i++) {
		printf("%2d | " , frame[i]);
	}
	if(hit == 1) printf("HIT\n");
	else printf("*\n");
}

int replace(int ref[] ,int n ,int frame[] ,int framesize ,int start) {
	int i;
	for(i = 0; i < framesize; i++) {
		if(frame[i] == -1) return i;
	}
	
	int j , rep = 0 , max = -999;
	for(i = 0; i < framesize; i++) {
		int cur = frame[i];
		for(j = start; j < n; j++) {
			if(cur == ref[j]) break;
		}
		if(j > max) {
			max = j;
			rep = i;
		}
	}
	return rep;
}

void opt(int ref[] , int framesize , int n) {
	int frame[framesize];
	int i;
	for(i = 0; i < framesize; i++) frame[i] = -1;
	int hit = 0 , pf = 0;
	
	for(i = 0; i < n; i++) {
		int cur = ref[i];
		if(find(frame , framesize , cur) == 0) {
			pf++;
			int rep = replace(ref , n , frame , framesize , i+1);
			frame[rep] = cur;
			display(frame , framesize , 0);
		} else {
			hit++;
			display(frame , framesize , 1);
		}
	}
}

int main() {
	int ref[] = {12,15,12, 18 , 6,8, 11 ,12 , 19 , 12, 6 , 8 , 12  ,15 , 19 , 8};
  	int frameSize = 3;
	int n = 16;
    opt(ref , frameSize , n);
    return 0;
}       
        
    

Comments

Popular posts from this blog

Least Recently Used (LRU) page algorithm in c

LFU Page Replacement Algorithm in C