sneak/Jumpy.Shared/History.cs
Colin McMillen 826e308cfe add History data structure
GitOrigin-RevId: b327e9a0a43abff8aa53f4531e0168f99c38c46b
2020-02-13 14:46:11 -05:00

54 lines
1.4 KiB
C#

using System;
namespace Jumpy {
// A History is a queue of fixed length N that records the N most recent items Add()ed to it.
// The mostly-recently-added item is found at index 0; the least-recently-added item is at index
// N-1. Items older than the History's size are automatically dropped. The underlying
// implementation is a fixed-size circular array; insertion and access are O(1).
//
// Example:
// h = new History<int>(3);
// h.Add(2); h.Add(3); h.Add(5);
// Console.WriteLine("{0} {1} {2}", h[0], h[1], h[2]); // 5 3 2
// h.Add(7);
// Console.WriteLine("{0} {1} {2}", h[0], h[1], h[2]); // 7 5 3
// h.Add(11); h.Add(13);
// Console.WriteLine("{0} {1} {2}", h[0], h[1], h[2]); // 13 11 7
class History<T> {
// Backing store for the History's items.
private T[] items;
// Points at the most-recently-inserted item.
private int idx = 0;
public History(int length) {
items = new T[length];
}
public void Add(T item) {
idx++;
if (idx >= items.Length) {
idx -= items.Length;
}
items[idx] = item;
}
public int Length {
get => items.Length;
}
public T this[int age] {
get {
if (age < 0 || age >= items.Length) {
throw new IndexOutOfRangeException();
}
int lookup = idx - age;
if (lookup < 0) {
lookup += items.Length;
}
return items[lookup];
}
}
}
}