Skip to content

Instantly share code, notes, and snippets.

@ozzi-
Created August 9, 2021 10:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ozzi-/3c3b7b0becef9027537fc6e6fb86a3f2 to your computer and use it in GitHub Desktop.
Save ozzi-/3c3b7b0becef9027537fc6e6fb86a3f2 to your computer and use it in GitHub Desktop.
import java.util.Collections;
public class RingBuffer<T> {
int length;
int currentPos = 0;
int firstPos = 0;
int lastPos;
private T[] buffer;
@SuppressWarnings("unchecked")
public RingBuffer(int length) {
this.length = length;
this.lastPos = length-1;
this.buffer = (T[]) new Object[length];
}
public void put(T v) {
buffer[currentPos]=v;
dumpContent(true,v);
currentPos++;
flowPos();
}
public T pop() {
currentPos--;
flowPos();
T v = buffer[currentPos];
buffer[currentPos]=null;
dumpContent(false,v);
return v;
}
public void flowPos() {
if(currentPos<firstPos) {
currentPos=lastPos;
}else if(currentPos>lastPos) {
currentPos=firstPos;
}
}
private void dumpContent(boolean put,T v) {
int spaceCount = 0;
for (int i = 0; i < buffer.length; i++) {
String out = "["+i+"] = "+buffer[i]+", ";
if(i<currentPos) {
spaceCount+=out.length();
}
System.out.print(out);
}
String action = (put?"PUT":"POP")+"="+v;
System.out.println("\r\n"+String.join("", Collections.nCopies(spaceCount, " "))+"/\\ "+action+"\r\n");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment