Design

Useful resources:

http://blog.gainlo.co/index.php/category/system-design-interview-questions/

http://javarevisited.blogspot.com/2012/06/20-design-pattern-and-software-design.html

https://www.palantir.com/how-to-ace-a-systems-design-interview/

https://hackernoon.com/top-10-system-design-interview-questions-for-software-engineers-8561290f0444

Ring Buffer

A ring buffer is an array with a fixed size, just like a bounded queue. The array contains the elements stored in the ring buffer.

public class RingBuffer<T> {
    private T[] elements = null;

    private int capacity = 0;
    private int writePos = 0;
    private int available = 0;

    public RingBuffer(int capacity) {
        this.capacity = capacity;
        this.elements = (T[]) new Object[capacity];
    }

    public void reset() {
        this.writePos = 0;
        this.available = 0;
    }

    public int getCapacity() {
        return this.capacity;
    }

    public int getAvailable() {
        return this.available;
    }

    public int remainingCapacity() {
        return this.capacity - this.available;
    }

    public boolean put(T element) {
        if(available==capacity) {
            return false;           //instead can throw underflow / overflow exception
        }
        available++;
        elements[writePos] = element;
        writePos++;
        if(writePos>=capacity) {
            writePos = 0;
        }
        return true;
    }

    public T take() {
        if(available==0) {
            return null;
        }
        int readPos = writePos - available;
        if (readPos<0) {
            readPos += capacity;
        }
        available--;
        return elements[readPos];
    }
}

results matching ""

    No results matching ""