Last active
December 16, 2015 07:38
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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