Program for Least Recently Used ( LRU ) Page Replacement algorithm | Method to find page faults using indexes ; To represent set of current pages . We use an unordered_set so that we quickly check if a page is present in set or not ; To store least recently used indexes of pages . ; Start from initial page ; Check if the set can hold more pages ; Insert it into set if not present already which represents page fault ; increment page fault ; Store the recently used index of each page ; If the set is full then need to perform lru i . e . remove the least recently used page and insert the current page ; Check if current page is not already present in the set ; Find the least recently used pages that is present in the set ; Remove the indexes page ; remove lru from hashmap ; insert the current page ; Increment page faults ; Update the current page index ; Driver method
function pageFaults ( pages , n , capacity ) { let s = new Set ( ) ; let indexes = new Map ( ) ; let page_faults = 0 ; for ( let i = 0 ; i < n ; i ++ ) { if ( s . size < capacity ) { if ( ! s . has ( pages [ i ] ) ) { s . add ( pages [ i ] ) ; page_faults ++ ; } indexes . set ( pages [ i ] , i ) ; } else { if ( ! s . has ( pages [ i ] ) ) { let lru = Number . MAX_VALUE , val = Number . MIN_VALUE ; for ( let itr of s . values ( ) ) { let temp = itr ; if ( indexes [ temp ] < lru ) { lru = indexes [ temp ] ; val = temp ; } } s . delete ( val ) ; indexes . delete ( val ) ; s . add ( pages [ i ] ) ; page_faults ++ ; } indexes . set ( pages [ i ] , i ) ; } } return page_faults ; } let pages = [ 7 , 0 , 1 , 2 , 0 , 3 , 0 , 4 , 2 , 3 , 0 , 3 , 2 ] ; let capacity = 4 ; document . write ( pageFaults ( pages , pages . length , capacity ) ) ;