Skip to content

Instantly share code, notes, and snippets.

@JoeRobich
Last active December 16, 2015 07:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JoeRobich/5399725 to your computer and use it in GitHub Desktop.
Save JoeRobich/5399725 to your computer and use it in GitHub Desktop.
Helpful utility for tracking which item in a group occurs at high enough of a frequency to call the confident item.
public class ConfidenceStore<T> where T : class
{
public event EventHandler<EventArgs<T>> Changed;
private Queue<T> queue;
private int length;
private int threshold;
private T confidentItem;
public ConfidenceStore(int length, int threshold)
{
if (threshold < (length / 2))
throw new ArgumentException("Threshold must be larger than half of the length.");
this.length = length;
this.threshold = threshold;
this.queue = new Queue<T>(length);
this.confidentItem = default(T);
}
public T ConfidentItem
{
get { return this.confidentItem; }
}
public void Add(T item)
{
if (this.queue.Count == this.length)
this.queue.Dequeue();
this.queue.Enqueue(item);
CheckForChangeInConfidence();
}
private void CheckForChangeInConfidence()
{
T confidentItem = FindConfidentItem();
if (ConfidentItem != confidentItem)
{
this.confidentItem = confidentItem;
OnChanged(ConfidentItem);
}
}
private T FindConfidentItem()
{
Dictionary<T, int> itemMap = new Dictionary<T, int>();
foreach (var item in this.queue)
{
int count = 0;
itemMap.TryGetValue(item, out count);
count++;
if (count >= this.threshold)
return item;
itemMap[item] = count;
}
return default(T);
}
protected void OnChanged(T confidentItem)
{
if (Changed != null)
Changed(this, new EventArgs<T>(confidentItem));
}
}
public class EventArgs<T> : EventArgs
{
private T _item;
public EventArgs(T item)
{
_item = item;
}
public T Item
{
get { return _item; }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment