I need a ring list dictionary that can store key and item. Capacity = 50 and when I add #51 the first item must be removed. Basically it must be a dictionary that behaves like a ring list.
Is there something in .NET Framework that can do that ? Or do I have to write it by myself ?
You won't find anything built-in I think but you can easily implement one using OrderedDictionary
OrderedDictionary maintains items in order which they are inserted. Whenever you reach the limit/capacity you can remove the first item.
or use an extension method :
EDIT :
because
latest added entry ends up being returned first.
so
u can remove the first item like :
dictionary.Remove(dictionary.Last().Key);
& so your extension method is :
addExtension(this Dictionary<string, object> dictionary, string key, object value)
{
if(dictionary.Count == 50)
dictionary.Remove(dictionary.Last().Key);
dictionary.Add(key, value);
}
Try this:
class Program
{
static void Main(string[] args)
{
var rD = new RingDictionary(50);
for (int i = 0; i < 75; i++)
{
rD.Add(i, i);
}
foreach (var item in rD.Keys)
{
Console.WriteLine("{0} {1}", item, rD[item]);
}
}
}
class RingDictionary : OrderedDictionary
{
int indexKey;
int _capacity = 0;
public int Capacity
{
get { return _capacity; }
set
{
if (value <= 0)
{
var errorMessage = typeof(Environment)
.GetMethod(
"GetResourceString",
System.Reflection.BindingFlags.Static |
System.Reflection.BindingFlags.NonPublic,
null,
new Type[] { typeof(string) },
null)
.Invoke(null, new object[] {
"ArgumentOutOfRange_NegativeCapacity"
}).ToString();
throw new ArgumentException(errorMessage);
}
_capacity = value;
}
}
public RingDictionary(int capacity)
{
indexKey = -1;
Capacity = capacity;
}
public new void Add(object key, object value)
{
indexKey++;
if (base.Keys.Count > _capacity)
{
for (int i = base.Keys.Count-1; i >Capacity-1 ; i--)
{
base.RemoveAt(i);
}
}
if (base.Keys.Count == _capacity)
{
base.RemoveAt(indexKey % _capacity);
base.Insert(indexKey % _capacity, key, value);
}
else
{
base.Add(key, value);
}
}
}
Related
I'm writing a small programm right now in which I made a Paar class, where one object consists of a key and a value
class Paar
{
private object value1;
public Paar(string key, object value1)
{
this.key = key;
this.value = value1;
}
public string key;
public object value;
}
I made a Put and a Get method for the class. The Put method parses a new entry in the first open slot it finds and the Get method can be used to print an entry by calling the key, they're as following
private Paar[] getArray = new Paar[10];
public void Put(string key, object value)
{
int i = 0;
while (true)
{
if (getArray[i] == null)
{
break;
}
else
{
i++;
if (i == 10)
{
throw new Exception("All slots full");
}
}
}
getArray[i] = new Paar(key, value);
}
public object Get(string key)
{
for (int i = 0; i <= 9; i++)
{
Paar currentElement = getArray[i]
if (currentElement.key == key)
{
return currentElement.value;
}
}
throw new Exception("Invalid key");
}
"Problem" is, that when I have two entries with the same key, I can only print the first entry, while I'd like to add a function to the Put method that overwrites previous entries with the same key and prints the most recent entry.
E.g:
newMap.Put("Key2", "Value1"); newMap.Put("Key2", "Value2"); newMap.Put("Key2", "Value3");
Console.WriteLine(newMap.Get("Key2"));
would currently print Value1, while I'd like it to print Value3. Is there any way to achieve this?
Try following
public void Put(string key, object value)
{
for (var i = 0; i < getArray.Length; ++i)
{
if (getArray[i] == null || getArray[i].key == key)
{
getArray[i] = new Paar(key, value);
break;
}
if(i == getArray.Length - 1)
throw new Exception("All slots full");
}
}
I implemented tchelidze's answer since it was technically correct, but when later implementing a Remove method it didn't work properly all the time since it could also parse the duplicate key's entry into an empty slot if there happened to be one before the duplicate key's slot, because it either checked for an empty slot or a matching key. So I improved the function to go through two seperate loops.
public void Put(string key, object value)
{
for (int i = 0; i < getArray.Length; i++)
{
if (getArray[i] != null && getArray[i].key == key)
{
getArray[i] = new Paar(key, value);
return;
}
}
for (int i = 0; i < getArray.Length; i++)
{
if (getArray[i] == null)
{
getArray[i] = new Paar(key, value);
break;
}
else
{
if (i >= getArray.Length)
{
throw new Exception("All slots full");
}
}
}
}
I'm trying to solve questions of C# programming in testdome.com, but I found problem about performance. How to solve it?
BinarySearchTree
using System;
public class Node
{
public int Value { get; set; }
public Node Left { get; set; }
public Node Right { get; set; }
public Node(int value, Node left, Node right)
{
Value = value;
Left = left;
Right = right;
}
}
public class BinarySearchTree
{
public static bool Contains(Node root, int value)
{
Console.WriteLine("value=" + value);
if(root == null)
return false;
else if(root.Value == value)
return true;
else if(root.Value != value)
{
return Contains(root.Left, value) | Contains(root.Right, value);
}
return false;
}
public static void Main(string[] args)
{
Node n1 = new Node(1, null, null);
Node n3 = new Node(3, null, null);
Node n2 = new Node(2, n1, n3);
Console.WriteLine(Contains(n2, 3));
}
}
Performance test on a large tree: Memory limit exceeded
https://www.testdome.com/for-developers/solve-question/7482
TwoSum
using System;
using System.Collections.Generic;
class TwoSum
{
public static Tuple<int, int> FindTwoSum(IList<int> list, int sum)
{
for(int ctr1=0; ctr1<list.Count; ctr1++)
{
for(int ctr2=0; ctr2<list.Count; ctr2++)
{
if ((ctr1 != ctr2) && (list[ctr1]+list[ctr2] == sum))
return new Tuple<int, int>(ctr1, ctr2);
}
}
return null;
}
public static void Main(string[] args)
{
Tuple<int, int> indices = FindTwoSum(new List<int>() { 1, 3, 5, 7, 9 }, 12);
Console.WriteLine(indices.Item1 + " " + indices.Item2);
}
}
Performance test with a large number of elements: Time limit exceeded
https://www.testdome.com/for-developers/solve-question/8125
For the Binary search tree, testdome.com provides a hint "If a value being searched for is smaller than the value of the node, then the right subtree can be ignored." This cuts memory consumption by half.
public static bool Contains(Node root, int value) {
Console.WriteLine("value=" + value);
if (root == null) {
return false;
}
else if (value == root.Value) {
return true;
}
else if (value < root.Value) {
// Hint 2: If a value being searched for is smaller than the value of the node,
// then the right subtree can be ignored.
return Contains(root.Left, value);
}
else {
return Contains(root.Right, value);
}
return false;
}
For the TwoSum, if we assume that the values in the input array are unique, we can use a dictionary to look up an index by its value (in O(1) time). This relates to the hint "A dictionary can be used to store pre-calculated values, this may allow a solution with O(N) complexity."
// Write a function that, when passed a list and a target sum,
// returns, efficiently with respect to time used,
// two distinct zero-based indices of any two of the numbers,
// whose sum is equal to the target sum.
// If there are no two numbers, the function should return null.
public static Tuple<int, int> FindTwoSum(IList<int> list, int sum) {
if (list.Count < 2) {
return null;
}
// Hint 2: A dictionary can be used to store pre-calculated values,
// this may allow a solution with O(N) complexity.
var indexByValue = new Dictionary<int, int>();
for (var i = 0; i < list.Count; i++) {
var value = list[i];
// ensure that the values used as keys are unique
// this is OK because we only have to return any tuple matching the sum,
// therefore we can ignore any duplicate values
if (!indexByValue.ContainsKey(value)) {
indexByValue.Add(value, i);
}
}
for (var j = 0; j < list.Count; j++) {
var remainder = sum - list[j];
if (indexByValue.ContainsKey(remainder)) {
return new Tuple<int, int> (j, indexByValue[remainder]);
}
}
return null;
}
Simpler way to attack the problem. The above answers are good, but think the desired result can be found quicker.
public static Tuple<int, int> FindTwoSum(IList<int> list, int sum)
{
if (list.Count < 2) { return null; }
foreach (int i in list)
{
int result = sum - i;
if(list.Contains(result))
{
return new Tuple<int, int>(i, result);
}
}
return null;
}
For TwoSum, I found the below link that gives 100% pass on TestDome: Look for JonnyT's answer:
TwoSum 100% Pass
Below is the code as well:
PS: I am only providing this to help others, so please upvote JonnyT's answer instead of mine :)
public static Tuple<int, int> FindTwoSum(IList<int> list, int sum)
{
HashSet<int> hs = new HashSet<int>();
for (int i = 0; i < list.Count; i++)
{
var needed = sum - list[i];
if (hs.Contains(needed))
{
return Tuple.Create(list.IndexOf(needed), i);
}
hs.Add(list[i]);
}
return null;
}
public static void Main(string[] args)
{
Tuple<int, int> indices = FindTwoSum(new List<int>() { 3, 1, 5, 7, 5, 9 }, 10);
if (indices != null)
{
Console.WriteLine(indices.Item1 + " " + indices.Item2);
}
}
// This passes all tests
public static bool Contains(Node root, int value)
{
var result = false;
if (root == null) return result;
if (value == root.Value)
{
result = true;
}
else
{
if(value <= root.Value)
{
if(Contains(root.Left, value))
{
result = true;
}
}
else
{
return Contains(root.Right, value);
}
}
return result;
}
For Twosum:
public static Tuple<int, int> FindTwoSum(IList<int> list, int sum)
{
if (list.Count < 2)
{
return Tuple<int, int>(0,0);
}
for (var j = 0; j < list.Count; j++)
{
var remainder = sum - list[j];
if (list.Contains(remainder))
{
return new Tuple<int, int>(list[j], remainder);
}
}
return new Tuple<int, int>(0,0);
}
Does .Net provides generic form of NameValueCollection or an alternative to
Dictionary<string,List<T>> ?
Something like
Person john = new Person();
...
Person vick = new Person();
...
NameValueCollection<Person> stringToPerson = new NameValueCollection<Person>();
stringToPerson.Add("John",john)
stringToPerson.Add("Vick",vick)
Actually in my case am forced to rely on Dictionary<string,List<Peron>>, is there any other alternative?
Regards,
Jeez
There's no such thing built in to the BCL as far as I know. I would just write your own class which wraps a Dictionary<string, List<T>> internally and exposes appropriate methods (e.g., Add could add an element to the List<T> for the given key).
For example:
class NameValueCollection<T>
{
Dictionary<string, List<T>> _dict = new Dictionary<string, List<T>>();
public void Add(string name, T value)
{
List<T> list;
if (!_dict.TryGetValue(name, out list))
{
_dict[name] = list = new List<T>();
}
list.Add(value);
}
// etc.
}
The closest alternative is probably the ILookup<TKey, TElement> interface. At the moment, the only public type that implements it in the BCL is the immutable Lookup<TKey, TElement> class, an instance of which can be created with the Enumerable.ToLookup method. If you want a mutable type that implements the interface, you'll have to write one yourself; you can find an example implementation here.
In your case, you probably want an ILookup<string, Person>.
Oh, I see what you want to do now. You want to be able to add to the Person collection without having to create a new List each time. Extension methods to the rescue!
public static void SafeAdd<TValue>(this IDictionary<TKey, ICollection<TValue>> dict, TKey key, TValue value)
{
HashSet<T> container;
if (!dict.TryGetValue(key, out container))
{
dict[key] = new HashSet<TValue>();
}
dict[key].Add(value);
}
Usage:
var names = new Dictionary<string, ICollection<Person>>();
names.SafeAdd("John", new Person("John"));
Nothing inbuilt; there is Lookup<TKey,TValue> which operates as a multi-map, but that is immutable. I wrote a mutable EditableLookup<TKey,TValue> for MiscUtil which may help.
Generic NameValueCollection
What makes NameValueCollection special unlike Dictionary, is that one key can contain several elements.
The generic NameValueCollection<T> based on NameObjectCollectionBase is in the following code:
using System.Collections.Specialized;
namespace System.Collections.Generic
{
public class NameValueCollection<T> : NameObjectCollectionBase
{
private string[] _keys; // Cached keys.
private T[] _values; // Cached values.
// Resets the caches.
protected void InvalidateCachedArrays()
{
_values = null;
_keys = null;
}
// Converts ArrayLit to Array of T elements.
protected static T[] AsArray(ArrayList list)
{
int count = 0;
if (list == null || (count = list.Count) == 0)
return (T[])null;
T[] array = new T[count];
list.CopyTo(0, array, 0, count);
return array;
}
// Gets all values cache.
protected ArrayList GetAllValues()
{
int count = Count;
ArrayList arrayList = new ArrayList(count);
for (int i = 0; i < count; ++i)
{
arrayList.AddRange(Get(i));
}
return arrayList;
}
// Adds single value to collection.
public void Add(string name, T value)
{
InvalidateCachedArrays();
ArrayList arrayList = (ArrayList)BaseGet(name);
if (arrayList == null)
{
arrayList = new ArrayList(1);
if (value != null) arrayList.Add(value);
BaseAdd(name, arrayList);
}
else
{
if (value == null) return;
arrayList.Add(value);
}
}
// Adds range of values to collection.
public void Add(NameValueCollection<T> collection)
{
InvalidateCachedArrays();
int count = collection.Count;
for (int i = 0; i < count; i++)
{
string key = collection.GetKey(i);
T[] values = collection.Get(i);
foreach (var value in values)
{
Add(key, value);
}
}
}
// Set single value (prevoious values will be removed).
public void Set(string name, T value)
{
InvalidateCachedArrays();
BaseSet(name, new ArrayList(1) { value });
}
// Set range of values (prevoious values will be removed).
public void Set(string name, params T[] values)
{
InvalidateCachedArrays();
BaseSet(name, new ArrayList(values));
}
// Gets all values that paired with specified key.
public T[] Get(string name)
{
return AsArray((ArrayList)BaseGet(name));
}
// Gets all values at the specified index of collection.
public T[] Get(int index)
{
return AsArray((ArrayList)BaseGet(index));
}
// Gets string containing the key at the specified index.
public string GetKey(int index)
{
return BaseGetKey(index);
}
// Removes values from the specified key.
public void Remove(string name)
{
InvalidateCachedArrays();
BaseRemove(name);
}
// Removes all data from the collection.
public void Clear()
{
InvalidateCachedArrays();
BaseClear();
}
// All keys that the current collection contains.
public new string[] Keys
{
get
{
if (_keys == null)
_keys = BaseGetAllKeys();
return _keys;
}
}
// All values that the current collection contains.
public T[] Values
{
get
{
if (_values == null)
_values = AsArray(GetAllValues());
return _values;
}
}
// Values at the specefied index.
public T[] this[int index]
{
get
{
return Get(index);
}
set
{
BaseSet(index, new ArrayList(value));
}
}
// Values at the specefied key.
public T[] this[string name]
{
get
{
return Get(name);
}
set
{
BaseSet(name, new ArrayList(value));
}
}
// Enumerates all entries.
public IEnumerable<KeyValuePair<string, T>> GetAllEntries()
{
foreach (string key in Keys)
{
foreach (T value in Get(key))
{
yield return new KeyValuePair<string, T>(key, value);
}
}
}
}
}
Usage:
NameValueCollection<int> collection = new NameValueCollection<int>();
collection.Add("a", 123);
collection.Add("a", 456); // 123 and 456 will be inserted into the same key.
collection.Add("b", 789); // 789 will be inserted into another key.
int[] a = collection.Get("a"); // contains 123 and 456.
int[] b = collection.Get("b"); // contains 789.
The above code implements the main features.
Here is complete implementation of the NameValueCollection<T> with additional tools.
I have a list of objects, of which I cannot know the type of at compile-time.
I need to identify any of these objects where a 'Count' property exists, and get the value if it does.
This code works for simple Collection types:
PropertyInfo countProperty = objectValue.GetType().GetProperty("Count");
if (countProperty != null)
{
int count = (int)countProperty.GetValue(objectValue, null);
}
The problem is that this doesn't work for generic types, such as IDictionary<TKey,TValue>. In those cases, the 'countProperty' value is returned as null, even though a 'Count' property exists in the instanced object.
All I want to do is identify any collection/dictionary based object and find the size of it, if it has one.
Edit: as requested, here's the entire listing of code that doesn't work
private static void GetCacheCollectionValues(ref CacheItemInfo item, object cacheItemValue)
{
try
{
//look for a count property using reflection
PropertyInfo countProperty = cacheItemValue.GetType().GetProperty("Count");
if (countProperty != null)
{
int count = (int)countProperty.GetValue(cacheItemValue, null);
item.Count = count;
}
else
{
//poke around for a 'values' property
PropertyInfo valuesProperty = cacheItemValue.GetType().GetProperty("Values");
int valuesCount = -1;
if (valuesProperty != null)
{
object values = valuesProperty.GetValue(cacheItemValue, null);
if (values != null)
{
PropertyInfo valuesCountProperty = values.GetType().GetProperty("Count");
if (countProperty != null)
{
valuesCount = (int)valuesCountProperty.GetValue(cacheItemValue, null);
}
}
}
if (valuesCount > -1)
item.Count = valuesCount;
else
item.Count = -1;
}
}
catch (Exception ex)
{
item.Count = -1;
item.Message = "Exception on 'Count':" + ex.Message;
}
}
This works OK on simple collections, but not on an object created from a class I have which is derived from Dictionary<TKey,TValue>. Ie
CustomClass :
Dictionary<TKey,TValue>
CacheItemInfo is just a simple class that contains properties for cache items - ie, key, count, type, expiration datetime
The first thing you should try is casting to ICollection, as this has a very cheap .Count:
ICollection col = objectValue as ICollection;
if(col != null) return col.Count;
The Count for dictionary should work though - I've tested this with Dictionary<,> and it works fine - but note that even if something implements IDictionary<,>, the concrete type (returned via GetType()) doesn't have to have a .Count on the public API - it could use explicit interface implementation to satisfy the interface while not having a public int Count {get;}. Like I say: it works for Dictionary<,> - but not necessarily for every type.
As a last ditch effort if everything else fails:
IEnumerable enumerable = objectValue as IEnumerable;
if(enumerable != null)
{
int count = 0;
foreach(object val in enumerable) count++;
return count;
}
Edit to look into the Dictionary<,> question raised in comments:
using System;
using System.Collections;
using System.Collections.Generic;
public class CustomClass : Dictionary<int, int> { }
public class CacheItemInfo
{
public int Count { get; set; }
public string Message { get; set; }
}
class Program {
public static void Main() {
var cii = new CacheItemInfo();
var data = new CustomClass { { 1, 1 }, { 2, 2 }, { 3, 3 } };
GetCacheCollectionValues(ref cii, data);
Console.WriteLine(cii.Count); // expect 3
}
private static void GetCacheCollectionValues(ref CacheItemInfo item, object cacheItemValue)
{
try
{
ICollection col;
IEnumerable enumerable;
if (cacheItemValue == null)
{
item.Count = -1;
}
else if ((col = cacheItemValue as ICollection) != null)
{
item.Count = col.Count;
}
else if ((enumerable = cacheItemValue as IEnumerable) != null)
{
int count = 0;
foreach (object val in enumerable) count++;
item.Count = count;
}
else
{
item.Count = -1;
}
}
catch (Exception ex)
{
item.Count = -1;
item.Message = "Exception on 'Count':" + ex.Message;
}
}
}
How about adding this after your first check (!untested!) ...
foreach (Type interfaceType in objectValue.GetType().GetInterfaces())
{
countProperty = interfaceType.GetProperty("Count");
//etc.
}
I'm looking for a .Net implementation of a multiset. Can anyone recommend a good one?
(A multiset, or bag, is a set that can have duplicate values, and on which you can do set operations: intersection, difference, etc. A shopping cart for instance could be thought of as a multiset because you can have multiple occurrences of the same product.)
I do not know about one, however you could use a Dictionary for that, in which the value is the quantity of the item. And when the item is added for the second time, you vould increase the value for it in the dictionary.
An other possibility would be to simply use a List of items, in which you could put duplicates. This might be a better approach for a shopping cart.
Anything calling itself a C# implementation of a multiset should not be based on a Dictionary internally. Dictionaries are hash tables, unordered collections. C++'s sets, multisets, maps, and multimaps are ordered. Internally each is represented as some flavor of a self-balancing binary search tree.
In C# we should then use a SortedDictionary as the basis of our implementation as according to Microsoft's own documentation a SortedDictionary "is a binary search tree with O(log n) retrieval". A basic multiset can be implemented as follows:
public class SortedMultiSet<T> : IEnumerable<T>
{
private SortedDictionary<T, int> _dict;
public SortedMultiSet()
{
_dict = new SortedDictionary<T, int>();
}
public SortedMultiSet(IEnumerable<T> items) : this()
{
Add(items);
}
public bool Contains(T item)
{
return _dict.ContainsKey(item);
}
public void Add(T item)
{
if (_dict.ContainsKey(item))
_dict[item]++;
else
_dict[item] = 1;
}
public void Add(IEnumerable<T> items)
{
foreach (var item in items)
Add(item);
}
public void Remove(T item)
{
if (!_dict.ContainsKey(item))
throw new ArgumentException();
if (--_dict[item] == 0)
_dict.Remove(item);
}
// Return the last value in the multiset
public T Peek()
{
if (!_dict.Any())
throw new NullReferenceException();
return _dict.Last().Key;
}
// Return the last value in the multiset and remove it.
public T Pop()
{
T item = Peek();
Remove(item);
return item;
}
public IEnumerator<T> GetEnumerator()
{
foreach(var kvp in _dict)
for(int i = 0; i < kvp.Value; i++)
yield return kvp.Key;
}
IEnumerator IEnumerable.GetEnumerator()
{
return this.GetEnumerator();
}
}
Another option is to just wrap SortedSet, but instead of storing your type T in it, you store the value tuple (T value, int counter) where counter goes up by 1 with each new instance of value that is inserted. Essentially you're forcing the values to be distinct. You can efficiently use GetViewBetween() to find the largest value of counter for a particular value, then increment it to get the counter for a newly-added value. And unlike the count dictionary solution, you can use GetViewBetween() to replicate the functionality equal_range, lower_bound, and upper_bound gives in C++. Here is some code showing what I mean:
public class SortedMultiSet<T> : IEnumerable<T>
{
public void Add(T value)
{
var view = set.GetViewBetween((value, 0), (value, int.MaxValue));
int nextCounter = view.Count > 0 ? view.Max.counter + 1 : 0;
set.Add((value, nextCounter));
}
public bool RemoveOne(T value)
{
var view = set.GetViewBetween((value, 0), (value, int.MaxValue));
if (view.Count == 0) return false;
set.Remove(view.Max);
return true;
}
public bool RemoveAll(T value)
{
var view = set.GetViewBetween((value, 0), (value, int.MaxValue));
bool result = view.Count > 0;
view.Clear();
return result;
}
public SortedMultiSet<T> GetViewBetween(T min, T max)
{
var result = new SortedMultiSet<T>();
result.set = set.GetViewBetween((min, 0), (max, int.MaxValue));
return result;
}
public IEnumerator<T> GetEnumerator() =>
set.Select(x => x.value).GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() =>
set.Select(x => x.value).GetEnumerator();
private SortedSet<(T value, int counter)> set =
new SortedSet<(T value, int counter)>();
}
Now you can write something like this:
var multiset = new SortedMultiSet<int>();
foreach (int i in new int[] { 1, 2, 2, 3, 4, 5, 5, 6, 7, 7, 8 })
{
multiset.Add(i);
}
foreach (int i in multiset.GetViewBetween(2, 7))
{
Console.Write(i + " "); // Output: 2 2 3 4 5 5 6 7 7
}
In the past, there were some issues where GetViewBetween() ran in time O(output size), rather than time O(log n), but I think those have been resolved. At the time it would count up nodes to cache the count, it now uses hierarchical counts to perform Count operations efficiently. See this StackOverflow post and this library code.
public class Multiset<T>: ICollection<T>
{
private readonly Dictionary<T, int> data;
public Multiset()
{
data = new Dictionary<T, int>();
}
private Multiset(Dictionary<T, int> data)
{
this.data = data;
}
public void Add(T item)
{
int count = 0;
data.TryGetValue(item, out count);
count++;
data[item] = count;
}
public void Clear()
{
data.Clear();
}
public Multiset<T> Except(Multiset<T> another)
{
Multiset<T> copy = new Multiset<T>(new Dictionary<T, int>(data));
foreach (KeyValuePair<T, int> kvp in another.data)
{
int count;
if (copy.data.TryGetValue(kvp.Key, out count))
{
if (count > kvp.Value)
{
copy.data[kvp.Key] = count - kvp.Value;
}
else
{
copy.data.Remove(kvp.Key);
}
}
}
return copy;
}
public Multiset<T> Intersection(Multiset<T> another)
{
Dictionary<T, int> newData = new Dictionary<T, int>();
foreach (T t in data.Keys.Intersect(another.data.Keys))
{
newData[t] = Math.Min(data[t], another.data[t]);
}
return new Multiset<T>(newData);
}
public bool Contains(T item)
{
return data.ContainsKey(item);
}
public void CopyTo(T[] array, int arrayIndex)
{
foreach (KeyValuePair<T, int> kvp in data)
{
for (int i = 0; i < kvp.Value; i++)
{
array[arrayIndex] = kvp.Key;
arrayIndex++;
}
}
}
public IEnumerable<T> Mode()
{
if (!data.Any())
{
return Enumerable.Empty<T>();
}
int modalFrequency = data.Values.Max();
return data.Where(kvp => kvp.Value == modalFrequency).Select(kvp => kvp.Key);
}
public int Count
{
get
{
return data.Values.Sum();
}
}
public bool IsReadOnly
{
get
{
return false;
}
}
public bool Remove(T item)
{
int count;
if (!data.TryGetValue(item, out count))
{
return false;
}
count--;
if (count == 0)
{
data.Remove(item);
}
else
{
data[item] = count;
}
return true;
}
public IEnumerator<T> GetEnumerator()
{
return new MultisetEnumerator<T>(this);
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return new MultisetEnumerator<T>(this);
}
private class MultisetEnumerator<T> : IEnumerator<T>
{
public MultisetEnumerator(Multiset<T> multiset)
{
this.multiset = multiset;
baseEnumerator = multiset.data.GetEnumerator();
index = 0;
}
private readonly Multiset<T> multiset;
private readonly IEnumerator<KeyValuePair<T, int>> baseEnumerator;
private int index;
public T Current
{
get
{
return baseEnumerator.Current.Key;
}
}
public void Dispose()
{
baseEnumerator.Dispose();
}
object System.Collections.IEnumerator.Current
{
get
{
return baseEnumerator.Current.Key;
}
}
public bool MoveNext()
{
KeyValuePair<T, int> kvp = baseEnumerator.Current;
if (index < (kvp.Value - 1))
{
index++;
return true;
}
else
{
bool result = baseEnumerator.MoveNext();
index = 0;
return result;
}
}
public void Reset()
{
baseEnumerator.Reset();
}
}
}
You can use this implementation of a sorted multiset: SortedMultiSet.cs