54 lines
1.4 KiB
C#
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];
|
|||
|
}
|
|||
|
}
|
|||
|
}
|
|||
|
}
|