Open In App

# Implementation of Least Recently Used (LRU) page replacement algorithm using Counters

Prerequisite – Least Recently Used (LRU) Page Replacement algorithm Least Recently Used page replacement algorithm replaces the page which is not used recently. Implementation: In this article, LRU is implemented using counters, a ctime (i.e., counter) variable is used to represent the current time, it is incremented for every page of the reference array. A vector of pair is used to represent the page frames, the 1’st variable of the pair is the page number and the second variable is the current time. When a new page is to be inserted and the frames are full, the page with minimum ctime is deleted (as it is the least recently used page). If the page is accessed again the value of ctime is updated. Note: Least ctime (counter / current time) value represents the least recently used page. Examples:

```Reference array is : 0, 0, 0, 2, 3, 0, 5, 7, 1, 2, 0, 8
Output :
When the number of frames is : 3
The number of page faults are : 9

Reference array is : 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 0, 0
Output :
When the number of frames is : 3
The number of page faults are : 15 ```

Code:

## CPP

 `#include ``  ` `using` `namespace` `std;``  ` `// To calculate the number of page faults``void` `pageFaults(``int` `frame_size, ``int``* ref, ``int` `len, ``int` `ctime``)``{``    ``// Count variable to count the``    ``// number of page faults``    ``int` `cnt = 0;``    ``// Arr to simulate frames``    ``vector > arr;``  ` `    ``// To initialise the array``    ``for` `(``int` `i = 0; i < frame_size; i++) {``        ``arr.push_back(make_pair(-1, ``ctime``));``    ``}``  ` `    ``int` `page;``  ` `    ``for` `(``int` `i = 0; i < len; i++) {``        ``page = ref[i];``        ``auto` `it = arr.begin();``  ` `        ``for` `(it = arr.begin(); it != arr.end(); it++) {``            ``if` `(it->first == page) {``                ``break``;``            ``}``        ``}``  ` `        ``// If page is found``        ``if` `(it != arr.end()) {``            ``// update the value of``            ``// current time``            ``it->second = ``ctime``;``        ``}``  ` `        ``// If page is not found``        ``else` `{``            ``// Find the page with min value of ctime,``            ``// as it will be the least recently used``            ``vector >::iterator pos;``            ``pos = arr.begin();``            ``int` `min = pos->second;``            ``for` `(``auto` `itr = arr.begin(); itr != arr.end(); itr++) {``                ``if` `(itr->second < min) {``                    ``pos = itr;``                    ``min = pos->second;``                ``}``            ``}``  ` `            ``// Erase this page from the frame vector``            ``arr.erase(pos);``  ` `            ``// Insert the new page``            ``arr.push_back(make_pair(page, ``ctime``));``            ``cnt++;``        ``}``        ``ctime``++;``    ``}``    ``cout << ``"The number of page faults is : "` `<< cnt << endl;``}``  ` `int` `main()``{``    ``// This is the reference array``    ``int` `ref[] = { 1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5 };``    ``int` `len = ``sizeof``(ref) / ``sizeof``(ref[0]);``    ``int` `frame_size = 3;``    ``// Ctime represents current time,``    ``// it is incremented for every page``    ``int` `ctime` `= 0;``    ``pageFaults(frame_size, ref, len, ``ctime``);``}`

## Javascript

 `// JavaScript implementation of the above approach` `// To calculate the number of page faults``function` `pageFaults(frame_size, ref, len, ctime)``{` `    ``// Count variable to count the``    ``// number of page faults``    ``let cnt = 0;``    ` `    ``// Arr to simulate frames``    ``let arr = [];` `    ``// To initialise the array``    ``for` `(let i = 0; i < frame_size; i++) {``        ``arr.push([-1, ctime]);``    ``}` `    ``let page;` `    ``for` `(let i = 0; i < len; i++) {``        ``page = ref[i];``        ``let it;` `        ``for` `(it = 0; it < arr.length; it++) {``            ``if` `(arr[it][0] == page) {``                ``break``;``            ``}``        ``}` `        ``// If page is found``        ``if` `(it != arr.length)``        ``{``        ` `            ``// update the value of``            ``// current time``            ``arr[it][1] = ctime;``        ``}` `        ``// If page is not found``        ``else``        ``{``        ` `            ``// Find the page with min value of ctime,``            ``// as it will be the least recently used``            ``let pos = 0;``            ``let min = arr[pos][1];``            ``for` `(let itr = 0; itr < arr.length; itr++) {``                ``if` `(arr[itr][1] < min) {``                    ``pos = itr;``                    ``min = arr[pos][1];``                ``}``            ``}` `            ``// Erase this page from the frame vector``            ``arr.splice(pos, 1);` `            ``// Insert the new page``            ``arr.push([page, ctime]);``            ``cnt++;``        ``}``        ``ctime++;``    ``}``    ``console.log(``"The number of page faults is : "` `+ cnt);``}` `// Driver code``function` `main()``{` `    ``// This is the reference array``    ``let ref = [1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5];``    ``let len = ref.length;``    ``let frame_size = 3;``    ` `    ``// Ctime represents current time,``    ``// it is incremented for every page``    ``let ctime = 0;``    ``pageFaults(frame_size, ref, len, ctime);``}` `main();` `// This code is contributed by phasing17`

## Python3

 `from` `typing ``import` `List``, ``Tuple` `def` `page_faults(frame_size: ``int``, ref: ``List``[``int``], ctime: ``int``) ``-``> ``int``:``    ``# Count variable to count the number of page faults``    ``cnt ``=` `0``    ``# Arr to simulate frames``    ``arr ``=` `[]``    ``# To initialise the array``    ``for` `i ``in` `range``(frame_size):``        ``arr.append((``-``1``, ctime))` `    ``for` `i ``in` `range``(``len``(ref)):``        ``page ``=` `ref[i]``        ``it ``=` `None``        ``for` `j ``in` `range``(``len``(arr)):``            ``if` `arr[j][``0``] ``=``=` `page:``                ``it ``=` `j``                ``break` `        ``# If page is found``        ``if` `it ``is` `not` `None``:``            ``# update the value of current time``            ``arr[it] ``=` `(page, ctime)` `        ``# If page is not found``        ``else``:``            ``# Find the page with min value of ctime,``            ``# as it will be the least recently used``            ``pos ``=` `0``            ``mn ``=` `arr[``0``][``1``]``            ``for` `j ``in` `range``(``1``, ``len``(arr)):``                ``if` `arr[j][``1``] < mn:``                    ``pos ``=` `j``                    ``mn ``=` `arr[j][``1``]` `            ``# Erase this page from the frame vector``            ``arr.pop(pos)` `            ``# Insert the new page``            ``arr.append((page, ctime))``            ``cnt ``+``=` `1``        ``ctime ``+``=` `1``    ``return` `cnt` `def` `main():``    ``# This is the reference array``    ``ref ``=` `[``1``, ``2``, ``3``, ``4``, ``1``, ``2``, ``5``, ``1``, ``2``, ``3``, ``4``, ``5``]``    ``frame_size ``=` `3``    ``# Ctime represents current time, it is incremented for every page``    ``ctime ``=` `0``    ``print``(``"The number of page faults is:"``, page_faults(frame_size, ref, ctime))` `if` `__name__ ``=``=` `'__main__'``:``    ``main()`

## C#

 `using` `System;``using` `System.Collections.Generic;` `public` `class` `GFG {``  ` `  ``// To calculate the number of page faults``  ``static` `void` `pageFaults(``int` `frame_size, ``int``[] refs,``                         ``int` `len, ``int` `ctime)``  ``{` `    ``// Count variable to count the``    ``// number of page faults``    ``int` `cnt = 0;` `    ``// Arr to simulate frames``    ``List > arr``      ``= ``new` `List >();` `    ``// To initialise the array``    ``for` `(``int` `i = 0; i < frame_size; i++) {``      ``arr.Add(``new` `Tuple<``int``, ``int``>(-1, ctime));``    ``}` `    ``int` `page;` `    ``for` `(``int` `i = 0; i < len; i++) {``      ``page = refs[i];``      ``int` `it;` `      ``for` `(it = 0; it < arr.Count; it++) {``        ``if` `(arr[it].Item1 == page) {``          ``break``;``        ``}``      ``}` `      ``// If page is found``      ``if` `(it != arr.Count) {``        ``// update the value of``        ``// current time``        ``Tuple<``int``, ``int``> temp = arr[it];``        ``temp = Tuple.Create(temp.Item1, ctime);``        ``arr[it] = temp;``      ``}` `      ``// If page is not found``      ``else` `{``        ``// Find the page with min value of ctime,``        ``// as it will be the least recently used``        ``int` `pos = 0;``        ``int` `min = arr[pos].Item2;``        ``for` `(``int` `itr = 0; itr < arr.Count; itr++) {``          ``if` `(arr[itr].Item2 < min) {``            ``pos = itr;``            ``min = arr[pos].Item2;``          ``}``        ``}` `        ``// Erase this page from the frame vector``        ``arr.RemoveAt(pos);` `        ``// Insert the new page``        ``arr.Add(``new` `Tuple<``int``, ``int``>(page, ctime));``        ``cnt++;``      ``}``      ``ctime++;``    ``}``    ``Console.WriteLine(``"The number of page faults is : "``                      ``+ cnt);``  ``}` `  ``public` `static` `void` `Main()``  ``{``    ``// This is the refserence array``    ``int``[] refs_arr = ``new` `int``[] { 1, 2, 3, 4, 1, 2,``                                ``5, 1, 2, 3, 4, 5 };``    ``int` `len = refs_arr.Length;``    ``int` `frame_size = 3;` `    ``// Ctime represents current time,``    ``// it is incremented for every page``    ``int` `ctime = 0;``    ``pageFaults(frame_size, refs_arr, len, ctime);``  ``}``}`

## Java

 `import` `java.util.*;` `class` `Main {``    ``public` `static` `void` `main(String[] args) {``        ``// This is the reference array``        ``int``[] ref = {``1``, ``2``, ``3``, ``4``, ``1``, ``2``, ``5``, ``1``, ``2``, ``3``, ``4``, ``5``};``        ``int` `len = ref.length;``        ``int` `frame_size = ``3``;` `        ``// Ctime represents current time,``        ``// it is incremented for every page``        ``int` `ctime = ``0``;``        ``pageFaults(frame_size, ref, len, ctime);``    ``}` `    ``// To calculate the number of page faults``    ``public` `static` `void` `pageFaults(``int` `frame_size, ``int``[] ref, ``int` `len, ``int` `ctime) {``        ``// Count variable to count the``        ``// number of page faults``        ``int` `cnt = ``0``;` `        ``// List to simulate frames``        ``List> arr = ``new` `ArrayList>();` `        ``// To initialise the list``        ``for` `(``int` `i = ``0``; i < frame_size; i++) {``            ``arr.add(``new` `Pair(-``1``, ctime));``        ``}` `        ``int` `page;` `        ``for` `(``int` `i = ``0``; i < len; i++) {``            ``page = ref[i];``            ``boolean` `found = ``false``;` `            ``// If page is found``            ``for` `(``int` `it = ``0``; it < arr.size(); it++) {``                ``if` `(arr.get(it).first == page) {``                    ``// update the value of``                    ``// current time``                    ``arr.get(it).second = ctime;``                    ``found = ``true``;``                    ``break``;``                ``}``            ``}` `            ``// If page is not found``            ``if` `(!found) {``                ``// Find the page with min value of ctime,``                ``// as it will be the least recently used``                ``int` `pos = ``0``;``                ``int` `min = arr.get(pos).second;``                ``for` `(``int` `itr = ``0``; itr < arr.size(); itr++) {``                    ``if` `(arr.get(itr).second < min) {``                        ``pos = itr;``                        ``min = arr.get(pos).second;``                    ``}``                ``}` `                ``// Erase this page from the frame list``                ``arr.remove(pos);` `                ``// Insert the new page``                ``arr.add(``new` `Pair(page, ctime));``                ``cnt++;``            ``}``            ``ctime++;``        ``}``        ``System.out.println(``"The number of page faults is : "` `+ cnt);``    ``}``}` `class` `Pair {``    ``public` `T first;``    ``public` `U second;` `    ``public` `Pair(T first, U second) {``        ``this``.first = first;``        ``this``.second = second;``    ``}``}`

Output:

`The number of page faults is : 10`