From 826e308cfe2a8b9ec94392718d058bc3920324a5 Mon Sep 17 00:00:00 2001 From: Colin McMillen Date: Tue, 10 Dec 2019 09:27:32 -0500 Subject: [PATCH] add History data structure GitOrigin-RevId: b327e9a0a43abff8aa53f4531e0168f99c38c46b --- Jumpy.Shared/History.cs | 53 +++++++++++++++++++++++++++++ Jumpy.Shared/Jumpy.Shared.projitems | 1 + 2 files changed, 54 insertions(+) create mode 100644 Jumpy.Shared/History.cs diff --git a/Jumpy.Shared/History.cs b/Jumpy.Shared/History.cs new file mode 100644 index 0000000..021911e --- /dev/null +++ b/Jumpy.Shared/History.cs @@ -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(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 { + + // 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]; + } + } + } +} diff --git a/Jumpy.Shared/Jumpy.Shared.projitems b/Jumpy.Shared/Jumpy.Shared.projitems index 6a595ce..e37ecde 100644 --- a/Jumpy.Shared/Jumpy.Shared.projitems +++ b/Jumpy.Shared/Jumpy.Shared.projitems @@ -11,6 +11,7 @@ +