Skip to content

Instantly share code, notes, and snippets.

@eaorak
Created October 31, 2012 12:44
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 eaorak/3986852 to your computer and use it in GitHub Desktop.
Save eaorak/3986852 to your computer and use it in GitHub Desktop.
Java - RoundArray<T>
package us.elron.utils.cache;
import java.lang.reflect.Array;
import java.util.Arrays;
/*
RoundArray can hold a "window" of values, oldest values are removed from
the array when new ones are added. It also supports console based simple
visualization.
*/
public class RoundArray<T extends Number> {
protected T[] array;
protected int size;
@SuppressWarnings("unchecked")
public RoundArray(Class<T> clazz,
int size) {
this.size = size;
this.array = (T[]) Array.newInstance(clazz, size);
}
public void put(T element) {
for (int i = this.array.length - 1; i > 0; i--) {
this.array[i] = this.array[i - 1];
}
this.array[0] = element;
}
public void reset(T value) {
Arrays.fill(this.array, value);
}
public T[] getAll() {
return this.getWindow(this.array.length);
}
public T[] getWindow(int length) {
int newLength = length > this.array.length ? this.array.length : length;
return Arrays.copyOf(this.array, newLength);
}
public String visualize(int height) {
StringBuilder graph = new StringBuilder();
T[] arr = this.array;
//
long max = this.max(arr);
max = max < 10 ? 10 : max;
float step = (1.0f * max) / height;
int space = String.valueOf(max).length();
//
for (int i = height; i > -1; i--) {
String line = String.format("%" + space + "d | ", (int) (i * step));
for (Number val : arr) {
int lineVal = Math.round(i * step);
val = (val == null) ? 0 : val;
line += val.longValue() >= lineVal ? " # " : " ";
}
graph.append(line + "\n");
}
for (int i = 0; i < arr.length; i++) {
graph.append("---");
}
graph.append("- : " + arr.length);
return graph.toString();
}
private long max(Number[] arr) {
Number max = 0;
for (Number val : arr) {
if (val == null) {
continue;
}
max = val.longValue() > max.longValue() ? val : max;
}
return max.longValue();
}
// Simple test
public static void main(String[] args) {
RoundArray<Long> array = new RoundArray<Long>(Long.class, 10);
for (long i = 0; i < 20; i++) {
array.put(i);
System.out.println(array.visualize(20));
}
for (long i = 20; i > 0; i--) {
array.put(i);
System.out.println(array.visualize(20));
}
for (long i = 20; i > 0; i--) {
array.put(0L);
System.out.println(array.visualize(20));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment