Circular Buffers: A data structure for O(1) random-indexing, append, prepend, clear, dropFirst and dropLast

Правка en2, от wrick, 2017-01-30 19:48:38

Circular buffers are simple data structures that provide O(1) get, set, append, prepend, clear, dropFirst and dropLast operations. It can be implemented using 2 pointers (start and end) and an array and using modular arithmetics for indexing.

Here is a simple implementation in Java:

public class CircularBuffer<T> {
  private T[] array = (T[]) (new Object[1<<10]);
  private int start = 0, end = 0;

  public T get(int i) {
    assert(0 <= i && i < size());
    return array[mod(start + i)];
  }

  public void set(int i, T elem) {
    assert(0 <= i && i < size());
    array[mod(start + i)] = elem;
  }

  public void append(T elem) {
    if (size() == array.length) resize();
    array[mod(end++)] = elem;
  }

  public void prepend(T elem) {
    if (size() == array.length) resize();
    array[mod(--start)] = elem;
  }

  public void dropFirst(int count) {
    assert(0 <= count && count <= size());
    start += count;
  }

  public void dropLast(int count) {
    assert(0 <= count && count <= size());
    end -= count;
  }

  public int size() {
    return mod(mod(end) - mod(start));
  }
  
  public void clear() {
    start = end = 0;
  }

  private int mod(int x) {
    return Math.floorMod(x, array.length);
  }

  private void resize() {
    T[] array2 = (T[])(new Object[2*array.length]);
    for(int i = 0; i < size(); i++) {
      array2[i] = get(i);
    }
    end = size();
    start = 0;
    array = array2;
  }
}

Source: https://gist.github.com/pathikrit/eac29538af53abf7e827a74e110fb0ac

Теги data structures

История

 
 
 
 
Правки
 
 
  Rev. Язык Кто Когда Δ Комментарий
en3 Английский wrick 2017-01-31 23:27:13 29
en2 Английский wrick 2017-01-30 19:48:38 112
en1 Английский wrick 2017-01-30 18:23:10 1625 Initial revision (published)