45 lines
1.3 KiB
Python
45 lines
1.3 KiB
Python
class Optimal:
|
|
def __init__(self, capacity):
|
|
self.capacity = capacity
|
|
self.cache = []
|
|
|
|
def refer(self, page, future):
|
|
if page not in self.cache:
|
|
if len(self.cache) < self.capacity:
|
|
self.cache.append(page)
|
|
else:
|
|
farthest_page = self.find_farthest_page(future)
|
|
index = self.cache.index(farthest_page)
|
|
self.cache[index] = page
|
|
|
|
def find_farthest_page(self, future):
|
|
farthest = -1
|
|
farthest_page = None
|
|
for page in self.cache:
|
|
if page not in future:
|
|
return page
|
|
try:
|
|
index = future.index(page)
|
|
if index > farthest:
|
|
farthest = index
|
|
farthest_page = page
|
|
except ValueError:
|
|
continue
|
|
return farthest_page
|
|
|
|
def display(self):
|
|
print("Current Pages in Memory (Optimal):", self.cache)
|
|
|
|
# Simulate Optimal Page Replacement
|
|
def optimal_simulation(pages, capacity):
|
|
optimal = Optimal(capacity)
|
|
for i in range(len(pages)):
|
|
optimal.refer(pages[i], pages[i + 1:])
|
|
optimal.display()
|
|
|
|
# Example Pages and Capacity
|
|
pages = [7, 0, 1, 2, 0, 3, 0, 4]
|
|
capacity = 3
|
|
print("\nOptimal Page Replacement Simulation:")
|
|
optimal_simulation(pages, capacity)
|