import
java.util.*;
public
class
Main {
static
boolean
findQueue(Queue<Integer> q,
int
x) {
for
(
int
i : q) {
if
(x == i)
return
true
;
}
return
false
;
}
static
void
LRU_Approximation(List<Integer> t,
int
capacity) {
int
n = t.size();
Queue<Integer> q =
new
LinkedList<>();
int
hits =
0
, faults =
0
;
boolean
[] bitref =
new
boolean
[capacity];
int
ptr =
0
;
int
count =
0
;
for
(
int
i =
0
; i < t.size(); i++) {
if
(!findQueue(q, t.get(i))) {
if
(count < capacity) {
q.add(t.get(i));
count++;
}
else
{
ptr =
0
;
while
(!q.isEmpty()) {
if
(bitref[ptr % capacity])
bitref[ptr % capacity] = !bitref[ptr % capacity];
else
break
;
ptr++;
}
if
(q.isEmpty()) {
q.poll();
q.add(t.get(i));
}
else
{
int
j =
0
;
while
(j < (ptr % capacity)) {
int
t1 = q.peek();
q.poll();
q.add(t1);
boolean
temp = bitref[
0
];
for
(
int
counter =
0
; counter < capacity -
1
; counter++)
bitref[counter] = bitref[counter +
1
];
bitref[capacity -
1
] = temp;
j++;
}
q.poll();
q.add(t.get(i));
}
}
faults++;
}
else
{
Queue<Integer> temp =
new
LinkedList<>(q);
int
counter =
0
;
while
(!q.isEmpty()) {
if
(q.peek() == t.get(i))
bitref[counter] =
true
;
counter++;
q.poll();
}
q = temp;
hits++;
}
}
System.out.println(
"Hits: "
+ hits +
"\nFaults: "
+ faults);
}
public
static
void
main(String[] args) {
List<Integer> t = Arrays.asList(
2
,
3
,
2
,
1
,
5
,
2
,
4
,
5
,
3
,
2
,
5
,
2
);
int
capacity =
4
;
LRU_Approximation(t, capacity);
}
}