add History data structure

GitOrigin-RevId: b327e9a0a43abff8aa53f4531e0168f99c38c46b
This commit is contained in:
Colin McMillen 2019-12-10 09:27:32 -05:00
parent fbbbdd14ee
commit 826e308cfe
2 changed files with 54 additions and 0 deletions

53
Jumpy.Shared/History.cs Normal file
View File

@ -0,0 +1,53 @@
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];
}
}
}
}

View File

@ -11,6 +11,7 @@
<ItemGroup>
<Compile Include="$(MSBuildThisFileDirectory)Camera.cs" />
<Compile Include="$(MSBuildThisFileDirectory)FpsCounter.cs" />
<Compile Include="$(MSBuildThisFileDirectory)History.cs" />
<Compile Include="$(MSBuildThisFileDirectory)IDisplay.cs" />
<Compile Include="$(MSBuildThisFileDirectory)KeyboardInput.cs" />
<Compile Include="$(MSBuildThisFileDirectory)JumpyGame.cs" />