-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path09.02.FIFO_Cache.java
More file actions
95 lines (79 loc) · 2.28 KB
/
09.02.FIFO_Cache.java
File metadata and controls
95 lines (79 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
9. Design, develop and implement a C/C++/Java program to implement page
replacement algorithms LRU and FIFO. Assume suitable input required to
demonstrate the results.
FIFO Part
*/
import java.util.Arrays;
import java.util.Scanner;
class CacheFIFO {
private static int[] cache;
private static int nF, nextFrameIndex = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter number of page requests");
int nR = scanner.nextInt();
int[] pageNumbers = new int[nR];
System.out.println("Enter page requests");
for (int i = 0; i < nR; ++i) {
pageNumbers[i] = scanner.nextInt();
}
System.out.println("Enter number of frames");
nF = scanner.nextInt();
cache = new int[nF];
Arrays.fill(cache, -1);
int totalHits = 0, totalMisses = 0;
for (int i = 0; i < nR; ++i) {
int index = findPageNumber(pageNumbers[i]);
if (index != -1) {
totalHits += 1;
} else {
totalMisses += 1;
cache[nextFrameIndex] = pageNumbers[i];
nextFrameIndex = (nextFrameIndex + 1) % nF;
}
printCache();
}
System.out.println("Total Hits " + totalHits);
System.out.println("Total Misses " + totalMisses);
float hitRatio = ((float) totalHits) / (totalHits + totalMisses);
System.out.println("Hit Ratio " + hitRatio);
}
public static int findPageNumber(int pageNumber) {
for (int i = 0; i < nF; ++i) {
if (cache[i] == pageNumber) {
return i;
}
}
return -1;
}
public static void printCache() {
System.out.print("Cache Content: ");
for (int i = 0; i < nF; ++i) {
System.out.print(cache[i] + " ");
}
System.out.println();
}
}
/*
Output:
Enter number of page requests
10
Enter page requests
2 3 5 4 2 5 7 3 8 7
Enter number of frames
3
Cache Content: 2 -1 -1
Cache Content: 2 3 -1
Cache Content: 2 3 5
Cache Content: 4 3 5
Cache Content: 4 2 5
Cache Content: 4 2 5
Cache Content: 4 2 7
Cache Content: 3 2 7
Cache Content: 3 8 7
Cache Content: 3 8 7
Total Hits 2
Total Misses 8
Hit Ratio 0.2
*/