//LRU algorithm //author:chillyCreator //in the page_information, the bigger number means the newer page. //if the number in the page_information is -1, it means no page is in this position. #include<iostream> usingnamespace std; boolisNotIn(int p_page_num); boolisNotFull(int& position); voidinsert(int p_page_num,int position); intdelOldPage(); constint MAX_INT = 32767; int process_num;//the total number of process pages int page_size;//the total number of pages int page_num=0;//the number of page which in the page array int miss=0;// int* page_information;//the page information array int* page;//the page array int old=0;//how old is a page? intmain() { cout << "how many pages of processes ?"<<endl; cin >> process_num ; cout << "how many pages in the memory?"<<endl; cin >> page_size; page_information = newint[page_size]; page = newint[page_size]; int i; for(i=0; i<page_size; i++) { page[i] = -1; page_information[i] = -1; } int user_test; cout << "input 1 is user test, 2 is auto test"<<endl; cin >> user_test; switch(user_test) { case1: for(i=0; i < process_num; i++) { int process_page_num; cin >> process_page_num; cout <<"input process page num is :" <<process_page_num<<endl; if(isNotIn(process_page_num)) { miss++; int temp_position; if(isNotFull(temp_position)) { insert(process_page_num,temp_position); page_num++; } else { temp_position = delOldPage(); insert(process_page_num,temp_position); } } } break; default: for(i=0; i < process_num; i++) { int process_page_num = rand(); cout << process_page_num<<endl; if(isNotIn(process_page_num)) { miss++; int temp_position; if(isNotFull(temp_position)) { insert(process_page_num,temp_position); page_num++; } else { temp_position = delOldPage(); insert(process_page_num,temp_position); } } } break; } cout <<"miss is " <<miss << "/t the total process num is "<<process_num<<endl; cout << endl; cout <<"the miss percentage is miss/process_num = "<<double(miss)/process_num<<endl; return0; } //the process page is in the page array?; boolisNotIn(int p_page_num) { for(int i=0; i<page_size; i++) { if(page[i]==p_page_num) returnfalse; } returntrue; } //the page array is full or not. //and return the empty position boolisNotFull(int& position) { if(page_size <= page_num) returnfalse; int i; for(i=0; i<page_size; i++) { if(page_information[i]==-1) break; } position = i; returntrue; } //insert a process page to the page in an empty position. //and the function protect the primite: old from flowover error. voidinsert(int p_page_num,int position) { old++; if(old==MAX_INT) { old = 1; for(int i=0; i<page_size; i++) { if(page_information[i]!=-1) page_information[i] = old; } } old++; page[position] = p_page_num; page_information[position] = old; } intdelOldPage() { int i; int min=page_information[0],min_i=0; for(i=1; i<page_size; i++) { if(min > page_information[i]) { min = page_information[i]; min_i = i; } } return min_i; }