|
using System;
using System.Collections.Generic;
using System.Text;
namespace QiHe.CodeLib
{
public class MultiSet<T>// : IEnumerable<T>
{
Dictionary<T, int> dict = new Dictionary<T, int>();
public MultiSet() { }
public MultiSet(IEnumerable<T> items)
{
foreach (T item in items)
{
Add(item);
}
}
public int Count
{
get { return dict.Count; }
}
public void Add(T item)
{
if (dict.ContainsKey(item))
{
dict[item] += 1;
}
else
{
dict[item] = 1;
}
}
public void AddRange(IEnumerable<T> items)
{
foreach (T item in items)
{
Add(item);
}
}
public void Remove(T item)
{
if (dict[item] > 1)
{
dict[item] -= 1;
}
else
{
dict.Remove(item);
}
}
public void Delete(T item)
{
dict.Remove(item);
}
public bool Contains(T item)
{
return dict.ContainsKey(item);
}
public void Clear()
{
dict = new Dictionary<T, int>();
}
public void SetOccur(T item, int occur)
{
dict[item] = occur;
}
public void AddOccur(T item, int occur)
{
if (!dict.ContainsKey(item))
{
dict[item] = 0;
}
dict[item] += occur;
}
public int GetOccur(T item)
{
return dict[item];
}
public T FindMaxOccur()
{
T item = default(T);
int max = 0;
foreach (KeyValuePair<T, int> pair in dict)
{
if (pair.Value > max)
{
item = pair.Key;
max = pair.Value;
}
}
return item;
}
public List<T> GetMinimumOccuredItems()
{
List<T> items = new List<T>();
int min = int.MaxValue;
foreach (KeyValuePair<T, int> pair in dict)
{
int occur = pair.Value;
if (occur < min)
{
min = occur;
items.Clear();
}
if (occur == min)
{
items.Add(pair.Key);
}
}
return items;
}
public List<Pair<T, int>> ConvertToList()
{
List<Pair<T, int>> pairs = new List<Pair<T, int>>(Count);
foreach (KeyValuePair<T, int> pair in dict)
{
pairs.Add(new Pair<T, int>(pair.Key, pair.Value));
}
return pairs;
}
public void LoadFromList(List<Pair<T, int>> pairs)
{
dict.Clear();
foreach (Pair<T, int> pair in pairs)
{
SetOccur(pair.Left, pair.Right);
}
}
/// <summary>
/// Sort in desendent order.
/// </summary>
/// <returns></returns>
public List<T> SortByOccur()
{
List<Pair<T, int>> pairs = ConvertToList();
pairs.Sort(delegate(Pair<T, int> one, Pair<T, int> other)
{
return other.Right - one.Right;
});
List<T> items = new List<T>(pairs.Count);
foreach (Pair<T, int> pair in pairs)
{
items.Add(pair.Left);
}
return items;
}
public Dictionary<T, int>.KeyCollection.Enumerator GetEnumerator()
{
return dict.Keys.GetEnumerator();
}
public IEnumerable<T> Items
{
get
{
return dict.Keys;
}
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.