Cache simulation elimination algorithm LRU (Java implementation)

Is also a surface examination questions, the topic is this:

Imagine a cache, if the data is returned to get success, if not get to the data, then returns a failure, regardless of ability to get to the data, always put
the latest record added to the cache, and the cache has a size limit, you can add unlimited but would squeeze out the previous data. If the cache size is given,

And gives a list of queries, with the program to simulate this process, and to obtain the number of a cache miss.

For example, input: int size = 4, int [ ] data = {1,2,3,4,3,5,3,2,1,5,4}
Output: 8

 The title given array, whether a cache hit process is as follows:

 In fact, he said the LRU algorithm is not very accurate, the Internet has a similar cache hit title, This question probably say that there will be a buffer, beginning with nothing, when slowly stored data will reach a given size, when insufficient buffer space, you need to do a clean-up buffer space, the so-called phase-out part of the data, this part of the data, from the title means, is that the first data is added to the cache, where the meaning of the questions, I gives this solution, we construct a queue, the default follow the FIFO (first in first Out) queue, the queue before each deposit, you need to determine whether the need to remove the head of the team element. Finally, we need to find a secondary method, traverse the queue, find the specified elements. Finally, a method is given: a cache miss is calculated by the number of the input array parameter.

The subject code as follows:

package com.xxx.algorithm;
import java.util.Iterator;
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
public class CacheDemo {
	private static Queue<Integer> queue = new ArrayBlockingQueue<Integer>(4);
	
	public static boolean find(int value){
		System.out.println(queue);
		Iterator<Integer> it = queue.iterator();
		while(it.hasNext()){
			int val = it.next();
			if(value==val)
				return true;
		}
		return false;
	}
	
	public static int get(int value){
		boolean exist = find(value);
		if(queue.size()==4){
			queue.poll();
		}
		queue.add(value);
		return exist?1:0;
	}
	
	public static int failCount(int[] data){
		int count = 0;
		for(int i=0;i<data.length;i++){
			if(get(data[i])==0){
				count++;
			}
		}
		return count;
	}
	
	public static void main(String[] args) {
		int[] data = {1,2,3,4,3,5,3,2,1,5,4};
		int count = failCount(data);
		System.out.println("failCount->"+count);
	}
}

 Print run results:

[]
[1]
[1, 2]
[1, 2, 3]
[1, 2, 3, 4]
[2, 3, 4, 3]
[3, 4, 3, 5]
[4, 3, 5, 3]
[3, 5, 3, 2]
[5, 3, 2, 1]
[3, 2, 1, 5]
failCount->8

This simple algorithm to meet the subject requirements. 

Guess you like

Origin blog.csdn.net/feinifi/article/details/94464696