2

I want to save 5 most recent int values. Code below uses int[] savedValues and current index counter store values.

public class MyBuffer {

    private final int BUFFER_SIZE = 5;
    int[] savedValues = new int[BUFFER_SIZE];
    int index  = 0;
    boolean isInitialCycle = true;


    public void save(int value){
        savedValues[index] = value;
        index++;
        if(index == BUFFER_SIZE){
            index = 0;
            isInitialCycle = false;
        }
    }

    public Integer restore(int stepsBack){
        if(( isInitialCycle && stepsBack > index ) || stepsBack > BUFFER_SIZE){
            return null;
        }
        int recordIndex = ( BUFFER_SIZE + index - stepsBack ) % BUFFER_SIZE;
        return savedValues[recordIndex];
    }    
}

What would be a cleaner way to keep track of most recent values?

Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129
Stepan
  • 1,391
  • 18
  • 40
  • 3
    Use a list. Remove the last element if the max size has been reached, and add the new element to the front. To restore, just take the Nth element from the list. – JB Nizet Nov 03 '17 at 07:38
  • 3
    There is a class ready for you [Size-limited queue that holds last N elements in Java](https://stackoverflow.com/questions/5498865/size-limited-queue-that-holds-last-n-elements-in-java) – Turo Nov 03 '17 at 07:47

1 Answers1

1

You can use inbuilt LinkedList class from java.

LinkedList<Integer> queue = new LinkedList<>();
queue.add(1);
queue.add(2);
Integer mostRecent = queue.getLast()//Gives most recent element
Integer leastRecent = queue.geFirst()//Gives least recent element

//To add new element if the buffer reaches
queue.removeFirst();
queue.add(3);
Raman Sharma
  • 1,940
  • 2
  • 11
  • 10