Move item up in IEnumerable - c#

I have a need to move an item in an IEnumerable<> up, that is move one item above another. What is the simplest way to do this?
A similar question was asked here but I don't have a generic list only an IEnumerable<>: Generic List - moving an item within the list

As #Brian commented the question is a little unclear as to what move an item in an IEnumerable<> up means.
If you want to reorder an IEnumerable for a single item then the code below should might be what you are looking for.
public static IEnumerable<T> MoveUp<T>(this IEnumerable<T> enumerable, int itemIndex)
{
int i = 0;
IEnumerator<T> enumerator = enumerable.GetEnumerator();
while (enumerator.MoveNext())
{
i++;
if (itemIndex.Equals(i))
{
T previous = enumerator.Current;
if (enumerator.MoveNext())
{
yield return enumerator.Current;
}
yield return previous;
break;
}
yield return enumerator.Current;
}
while (enumerator.MoveNext())
{
yield return enumerator.Current;
}
}

You can't. IEnumerable is only to iterate through some items, not for editing a list of items

You can use the ToList() extension method and use the answer from the question you referenced. e.g.
var list = enumerable.ToList();
//do stuff from other answer, and then convert back to enumerable if you want
var reorderedEnumerable = list.AsEnumerable();

I didn't find anything that would do what you want with IEnumerable<T>. Having developed similar stuff in the past for specific types of collections, list, arrays, etc, I felt it was time to take a better look at it. So I took a couple of minutes to write a generic version that could be applied to any IEnumerable<T>.
I did some basic testing and parameter checking but by no means consider them compreensive.
Given that disclaimer, let's get to the code:
static class Enumerable {
public static IEnumerable<T> MoveDown<T>(this IEnumerable<T> source, int index) {
if (source == null) {
throw new ArgumentNullException("source");
}
T[] array = source.ToArray();
if (index == array.Length - 1) {
return source;
}
return Swap<T>(array, index, index + 1);
}
public static IEnumerable<T> MoveDown<T>(this IEnumerable<T> source, T item) {
if (source == null) {
throw new ArgumentNullException("source");
}
T[] array = source.ToArray();
int index = Array.FindIndex(array, i => i.Equals(item));
if (index == -1) {
throw new InvalidOperationException();
}
if (index == array.Length - 1) {
return source;
}
return Swap<T>(array, index, index + 1);
}
public static IEnumerable<T> MoveUp<T>(this IEnumerable<T> source, int index) {
if (source == null) {
throw new ArgumentNullException("source");
}
T[] array = source.ToArray();
if (index == 0) {
return source;
}
return Swap<T>(array, index - 1, index);
}
public static IEnumerable<T> MoveUp<T>(this IEnumerable<T> source, T item) {
if (source == null) {
throw new ArgumentNullException("source");
}
T[] array = source.ToArray();
int index = Array.FindIndex(array, i => i.Equals(item));
if (index == -1) {
throw new InvalidOperationException();
}
if (index == 0) {
return source;
}
return Swap<T>(array, index - 1, index);
}
public static IEnumerable<T> Swap<T>(this IEnumerable<T> source, int firstIndex, int secondIndex) {
if (source == null) {
throw new ArgumentNullException("source");
}
T[] array = source.ToArray();
return Swap<T>(array, firstIndex, secondIndex);
}
private static IEnumerable<T> Swap<T>(T[] array, int firstIndex, int secondIndex) {
if (firstIndex < 0 || firstIndex >= array.Length) {
throw new ArgumentOutOfRangeException("firstIndex");
}
if (secondIndex < 0 || secondIndex >= array.Length) {
throw new ArgumentOutOfRangeException("secondIndex");
}
T tmp = array[firstIndex];
array[firstIndex] = array[secondIndex];
array[secondIndex] = tmp;
return array;
}
public static IEnumerable<T> Swap<T>(this IEnumerable<T> source, T firstItem, T secondItem) {
if (source == null) {
throw new ArgumentNullException("source");
}
T[] array = source.ToArray();
int firstIndex = Array.FindIndex(array, i => i.Equals(firstItem));
int secondIndex = Array.FindIndex(array, i => i.Equals(secondItem));
return Swap(array, firstIndex, secondIndex);
}
}
As you can see, MoveUp and MoveDown are basically Swap operations. With MoveUp you swap positions with the previous element and with MoveDown you swap positions with the next element.
Of course, that does not apply for moving up the first element or moving down the last element.
Running a quick test with the code below...
class Program {
static void Main(string[] args) {
int[] a = { 0, 2, 1, 3, 4 };
string[] z = { "Zero", "Two", "One", "Three", "Four" };
IEnumerable<int> b = Enumerable.Swap(a, 1, 2);
WriteAll(b);
IEnumerable<int> c = Enumerable.MoveDown(a, 1);
WriteAll(c);
IEnumerable<int> d = Enumerable.MoveUp(a, 2);
WriteAll(d);
IEnumerable<int> f = Enumerable.MoveUp(a, 0);
WriteAll(f);
IEnumerable<int> g = Enumerable.MoveDown(a, 4);
WriteAll(g);
IEnumerable<string> h = Enumerable.Swap(z, "Two", "One");
WriteAll(h);
var i = z.MoveDown("Two");
WriteAll(i);
var j = z.MoveUp("One");
WriteAll(j);
Console.WriteLine("Press any key to continue...");
Console.Read();
}
private static void WriteAll<T>(IEnumerable<T> b) {
foreach (var item in b) {
Console.WriteLine(item);
}
}
... it looks like everything is working well.
I hope it serves at least as a starting point for you.

I like this approach
/// <summary>
/// Extension methods for <see cref="System.Collections.Generic.List{T}"/>
/// </summary>
public static class ListExtensions
{
public static void MoveForward<T>(this List<T> list, Predicate<T> itemSelector, bool isLastToBeginning)
{
Ensure.ArgumentNotNull(list, "list");
Ensure.ArgumentNotNull(itemSelector, "itemSelector");
var currentIndex = list.FindIndex(itemSelector);
// Copy the current item
var item = list[currentIndex];
bool isLast = list.Count - 1 == currentIndex;
if (isLastToBeginning && isLast)
{
// Remove the item
list.RemoveAt(currentIndex);
// add the item to the beginning
list.Insert(0, item);
}
else if (!isLast)
{
// Remove the item
list.RemoveAt(currentIndex);
// add the item at next index
list.Insert(currentIndex + 1, item);
}
}
public static void MoveBack<T>(this List<T> list, Predicate<T> itemSelector, bool isFirstToEnd)
{
Ensure.ArgumentNotNull(list, "list");
Ensure.ArgumentNotNull(itemSelector, "itemSelector");
var currentIndex = list.FindIndex(itemSelector);
// Copy the current item
var item = list[currentIndex];
bool isFirst = 0 == currentIndex;
if (isFirstToEnd && isFirst)
{
// Remove the item
list.RemoveAt(currentIndex);
// add the item to the end
list.Add(item);
}
else if (!isFirstToEnd)
{
// Remove the item
list.RemoveAt(currentIndex);
// add the item to previous index
list.Insert(currentIndex - 1, item);
}
}
}

Related

Linq: ForEach item return the number of items needed to get n unique items starting at that item

Lets say I have a list of items:
[a,b,b,a,c,d,a,d,b,c]
and I need to know, for each item, how many items along do I have to traverse till I get n unique items, (and return eg -1, or otherwise indicate if that's not possible)
So here, if n = 4, I would return
[6,5,4,6,5,5,4,-1,-1,-1]
since
a,b,b,a,c,d contains 4 unique elements
b,b,a,c,d contains 4 unique elements
b,a,c,d contains 4 unique elements,
a,c,d,a,d,b contains 4 unique elements
etc.
I used
List.Select((x,i) => {
var range = List.Skip(i).GroupBy(y => y).Take(n);
if (range.Count() == n)
return range.SelectMany(y => y).Count();
return -1;
});
Although i'm pretty sure this is horribly non-performant.
To try to minimize overhead, I created a ListSpan extension class for managing subparts of a List - something like ArraySegment for List, but (loosely) modeled on Span:
public class ListSpan<T> : IEnumerable<T>, IEnumerable {
List<T> baseList;
int start;
int len;
public ListSpan(List<T> src, int start = 0, int? len = null) {
baseList = src;
this.start = start;
this.len = len ?? (baseList.Count - start);
if (this.start + this.len > baseList.Count)
throw new ArgumentException("start+len > Count for ListSpan");
}
public T this[int n]
{
get
{
return baseList[start + n];
}
set
{
baseList[start + n] = value;
}
}
public class ListSpanEnumerator<Te> : IEnumerator<Te>, IEnumerator {
int pos;
List<Te> baseList;
int end;
Te cur = default(Te);
public ListSpanEnumerator(ListSpan<Te> src) {
pos = src.start - 1;
baseList = src.baseList;
end = src.start + src.len;
}
public Te Current => cur;
object IEnumerator.Current => Current;
public bool MoveNext() {
if (++pos < end) {
cur = baseList[pos];
return true;
}
else {
cur = default(Te);
return false;
}
}
public void Reset() => pos = 0;
public void Dispose() { }
}
public IEnumerator<T> GetEnumerator() => new ListSpanEnumerator<T>(this);
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
public static class ListExt {
public static ListSpan<T> Slice<T>(this List<T> src, int start = 0, int? len = null) => new ListSpan<T>(src, start, len);
}
Then I created an extension method to return the distance (in Take terms) required to get n unique items from an IEnumerable:
public static class IEnumerableExt {
public static int DistanceToUnique<T>(this IEnumerable<T> src, int n, IEqualityComparer<T> cmp = null) {
var hs = new HashSet<T>(cmp ?? EqualityComparer<T>.Default);
var pos = 0;
using (var e = src.GetEnumerator()) {
while (e.MoveNext()) {
++pos;
hs.Add(e.Current);
if (hs.Count == n)
return pos;
}
}
return -1;
}
}
Now the answer is relatively straight forward:
var ans = Enumerable.Range(0, src.Count).Select(p => src.Slice(p).DistanceToUnique(n));
Basically I go through each position in the original (src) List and compute the distance to n unique values from that position using a ListSpan of the List starting at that position.
This still isn't terribly efficient in that I am creating a HashSet for every element in the original List and putting all the following elements in it, and traversing the elements up to k! times for a k element List. Still trying to come up with something really efficient.

How to clone part of a List?

Is it possible to clone just part of a List<T>?
Example:
List<string> myoriginalstring = new List<string>();
myoriginalstring.Add("Tyrannosaurus");
myoriginalstring.Add("Amargasaurus");
myoriginalstring.Add("Mamenchisaurus");
I want to clone myoriginalstring to another list but just from index 1 to index 2.
Is that possible? Changes in the second List<string> should be reflected in first and vice-versa.
UPDATE
Thanks for the answers so far. It seems I didn't express myself correctly.
Actually I don't want to copy or clone. I need to create a new list (which will be some part of the original one); and when I change something (some value) in my new list, the original should be also changed the same way. (The lists should be identical all the time, just the new list will be some part of the original).
Hopefully that is clearer.
You can create a ListSlice<T> class that represents a slice of an existing list. The slice will behave as a read-only list and because it keeps a reference to the original list you are not supposed to add or remove elements in the original list. This cannot be enforced unless you implement your own list but I will not do that here.
You will have to implement the entire IList<T> interface including the IEnumerator<T> you need for enumerating the slice. Here is an example:
class ListSlice<T> : IList<T> {
readonly IList<T> list;
readonly Int32 startIndex;
readonly Int32 length;
public ListSlice(IList<T> list, Int32 startIndex, Int32 length) {
if (list == null)
throw new ArgumentNullException("list");
if (!(0 <= startIndex && startIndex < list.Count))
throw new ArgumentException("startIndex");
if (!(0 <= length && length <= list.Count - startIndex))
throw new ArgumentException("length");
this.list = list;
this.startIndex = startIndex;
this.length = length;
}
public T this[Int32 index] {
get {
if (!(0 <= index && index < this.length))
throw new ArgumentOutOfRangeException();
return this.list[this.startIndex + index];
}
set {
if (!(0 <= index && index < this.length))
throw new ArgumentOutOfRangeException();
this.list[this.startIndex + index] = value;
}
}
public Int32 IndexOf(T item) {
var index = this.list.IndexOf(item);
return index == -1 || index >= this.startIndex + this.length
? -1 : index - this.startIndex;
}
public void Insert(Int32 index, T item) { throw new NotSupportedException(); }
public void RemoveAt(Int32 index) { throw new NotSupportedException(); }
public Int32 Count { get { return this.length; } }
public Boolean IsReadOnly { get { return true; } }
public void Add(T item) { throw new NotSupportedException(); }
public void Clear() { throw new NotSupportedException(); }
public Boolean Contains(T item) { return IndexOf(item) != -1; }
public void CopyTo(T[] array, Int32 arrayIndex) {
for (var i = this.startIndex; i < this.length; i += 1)
array[i + arrayIndex] = this.list[i];
}
public Boolean Remove(T item) { throw new NotSupportedException(); }
public IEnumerator<T> GetEnumerator() {
return new Enumerator(this.list, this.startIndex, this.length);
}
IEnumerator IEnumerable.GetEnumerator() {
return GetEnumerator();
}
class Enumerator : IEnumerator<T> {
readonly IList<T> list;
readonly Int32 startIndex;
readonly Int32 length;
Int32 index;
T current;
public Enumerator(IList<T> list, Int32 startIndex, Int32 length) {
this.list = list;
this.startIndex = startIndex;
this.length = length;
}
public T Current { get { return this.current; } }
Object IEnumerator.Current {
get {
if (this.index == 0 || this.index == this.length + 1)
throw new InvalidOperationException();
return Current;
}
}
public Boolean MoveNext() {
if (this.index < this.length) {
this.current = this.list[this.index + this.startIndex];
this.index += 1;
return true;
}
this.current = default(T);
return false;
}
public void Reset() {
this.index = 0;
this.current = default(T);
}
public void Dispose() {
}
}
}
You can write an extension method to make it easier to work with slices:
static class ListExtensions {
public static ListSlice<T> Slice<T>(this IList<T> list, Int32 startIndex, Int32 length) {
return new ListSlice<T>(list, startIndex, length);
}
}
To use the slice you can write code like this:
var list = new List<String> {
"Tyrannosaurus",
"Amargasaurus",
"Mamenchisaurus"
};
var slice = list.Slice(1, 2);
slice[0] = "Stegosaurus";
Now list[1] as well as slice[0] contains "Stegosaurus".
Assuming you really did mean clone and not copy...
List<string> myoriginalstring = new List<string> { "Tyrannosaurus", "Amargasaurus", "Mamenchisaurus" };
List<string> myCloneString = myoriginalstring.GetRange(1, myoriginalstring.Count() -1 );
On the first glance, it seems as if
var list2 = myoriginalstring.SkipWhile((str, i)=>!(i>=1 && i<=2)).ToList();
list2[1]="Stegosaurus";
would be the solution. But it is not, because list2 is a independent list which contains its own elements. The code above works, but it replaces only the element in the (new) list2, not in myoriginalstring.
As you pointed out, this is not what you wanted to do.
Solution
Unlike other languages like C, you don't have access to pointers directly in C#.
Hence, the solution is more complex. Instead of using strings directly, you need to create an object, like the following:
public class Dino
{
public string Value { get; set; }
public object[] Parent { get; set; }
public int ParentIndex;
}
Then, create some helper extension methods, like so:
public static class Extensions
{
public static Dino AsDino(this string name)
{
return new Dino() {Value=name};
}
public static Dino AsDino(this string name, object[] reference, int parentIndex)
{
return new Dino() {Value=name, Parent=reference, ParentIndex=parentIndex };
}
public static Dino Replace(this object item, Dino replacementItem)
{
replacementItem.ParentIndex=((Dino)item).ParentIndex;
replacementItem.Parent=((Dino)item).Parent;
((Dino)item).Parent[replacementItem.ParentIndex]=replacementItem;
return replacementItem;
}
}
With those helpers, you can do it:
// create array with 3 elements
var myoriginalstring = new object[3];
// fill in the dinosours and keep track of the array object and positions within
myoriginalstring[0]="Tyrannosaurus".AsDino(myoriginalstring, 0);
myoriginalstring[1]="Amargasaurus".AsDino(myoriginalstring, 1);
myoriginalstring[2]="Mamenchisaurus".AsDino(myoriginalstring, 2);
// get a subset of the array
var list2 = myoriginalstring.SkipWhile((str, i)=>!(i>=1 && i<=2)).ToList<object>();
// replace the value at index 1 in list2. This will also replace the value
// in the original array myoriginalstring
list2[1].Replace("Stegosaurus".AsDino());
The trick is, that the Dino class keeps track of its origin (the array myoriginalstring) and the position within it (i.e. its index).

Iterating an array with foreach backwards without using extension method

After making a search at the Google, I found this discussion:
Possible to iterate backwards through a foreach?
But in the answers there is used extension method .Reverse(). With reverse, the list of objects, for ie. List of Strings, wtill be reversed first, and foreach doesn't reverse the list with my understoodment? If I got list "Cat", "Dog", and use .Reverse() -method, the list will be "Dog", "Cat", and foreach starts from the 0 element till the lenght-1 -element and that's what I'm not looking for. I would want to know, if there was any way to reverse foreach iteration order, to start from lenght-1 down to 0.
if there was any way to reverse foreach iteration order, to start from length-1 down to 0
Not for a List<T>. The implementation of GetEnumerator() returns an enumerator that enumerates from beginning to end - there's no way to override that.
With a custom collection, then you'd just have to use a different enumerator that could go backwards, but there's no way to override the implementation that List<T> uses.
The Reverse method will copy the list first:
public static IEnumerable<TSource> Reverse<TSource>(this IEnumerable<TSource> source) {
if (source == null) throw Error.ArgumentNull("source");
return ReverseIterator<TSource>(source);
}
static IEnumerable<TSource> ReverseIterator<TSource>(IEnumerable<TSource> source) {
Buffer<TSource> buffer = new Buffer<TSource>(source);
for (int i = buffer.count - 1; i >= 0; i--) yield return buffer.items[i];
}
But you can do an extension method yourself:
public static IEnumerable<TSource> Backwards<TSource>(this IList<TSource> source) {
for (var i = source.Count - 1; i >= 0; --i)
yield return source[i];
}
And then use it like that:
foreach (var item in array.Backwards())
Console.WriteLine(item); // Or whatever else
Or, of course, you could just do the equivalent:
for (var i = array.Length - 1; i >= 0; --i)
Console.WriteLine(array[i]); // Or whatever else
You can implement an enumerator that iterates though a list backwards. That way you can use foreach without changing the original list or creating a copy of it.
public class ReverseEnumerator<T> : IEnumerator<T> {
private IList<T> _list;
private int _index;
private T _current;
public ReverseEnumerator(IList<T> list) {
_list = list;
Reset();
}
public IEnumerator<T> GetEnumerator() {
return this;
}
public T Current {
get {
if (_index < 0 && _index >= _list.Count) throw new InvalidOperationException("Enumeration has not started. Call MoveNext.");
return _current;
}
}
public void Dispose() { }
object IEnumerator.Current { get { return Current; } }
public bool MoveNext() {
bool ok = --_index >= 0;
if (ok) _current = _list[_index];
return ok;
}
public void Reset() {
_index = _list.Count;
}
}
Usage example:
int[] a = { 1, 2, 3, 4, 5 };
foreach (int x in new ReverseEnumerator<int>(a)) {
Console.WriteLine(x);
}

how to count continuous values in a list with linq

I've a list like this:
var query = Enumerable.Range(0, 999).Select((n, index) =>
{
if (index <= 333 || index >=777)
return 0;
else if (index <= 666)
return 1;
else
return 2;
});
So, Can I find how much indexes have same value continuously? For example;
query[0]=query[1]=query[2]=query[3]... = 0, query[334] = 1, query[777]=query[778]... = 0.
First 334 indexes have 0, so first answer is 333. Also Last 223 indexes have 0, so second answer is 223..
How can I find these and their indexes?
Thanks in advance.
You can create extension for consecutive grouping of items by some key:
public static IEnumerable<IGrouping<TKey, T>> GroupConsecutive<T, TKey>(
this IEnumerable<T> source, Func<T, TKey> keySelector)
{
using (var iterator = source.GetEnumerator())
{
if (!iterator.MoveNext())
yield break;
else
{
List<T> list = new List<T>();
var comparer = Comparer<TKey>.Default;
list.Add(iterator.Current);
TKey groupKey = keySelector(iterator.Current);
while (iterator.MoveNext())
{
var key = keySelector(iterator.Current);
if (!list.Any() || comparer.Compare(groupKey, key) == 0)
{
list.Add(iterator.Current);
continue;
}
yield return new Group<TKey, T>(groupKey, list);
list = new List<T> { iterator.Current };
groupKey = key;
}
if (list.Any())
yield return new Group<TKey, T>(groupKey, list);
}
}
}
Of course you can return IEnumerable<IList<T>> but that will be a little different from concept of group, which you want to have, because you also want to know which value was used to group sequence of items. Unfortunately there is no public implementation of IGrouping<TKey, TElement> interface, and we should create our own:
public class Group<TKey, TElement> : IGrouping<TKey, TElement>
{
private TKey _key;
private IEnumerable<TElement> _group;
public Group(TKey key, IEnumerable<TElement> group)
{
_key = key;
_group = group;
}
public TKey Key
{
get { return _key; }
}
public IEnumerator<TElement> GetEnumerator()
{
return _group.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
Now usage is very simple:
var groups = query.GroupConsecutive(i => i) // produces groups
.Select(g => new { g.Key, Count = g.Count() }); // projection
Result:
[
{ Key: 0, Count: 334 },
{ Key: 1, Count: 333 },
{ Key: 2, Count: 110 },
{ Key: 0, Count: 222 }
]
Using the GroupConsecutive extension method from here you can just get the counts of each group:
query.GroupConsecutive((n1, n2) => n1 == n2)
.Select(g => new {Number = g.Key, Count = g.Count()})
public static IEnumerable<int> GetContiguousCounts<T>(this IEnumerable<T> l, IEqualityComparer<T> cmp)
{
var last = default(T);
var count = 0;
foreach (var e in l)
{
if (count > 0 && !cmp.Equals(e, last))
{
yield return count;
count = 0;
}
count++;
last = e;
}
if (count > 0)
yield return count;
}
public static IEnumerable<int> GetContiguousCounts<T>(this IEnumerable<T> l)
{
return GetContiguousCounts(l, EqualityComparer<T>.Default);
}
static void Main(string[] args)
{
var a = new[] { 1, 2, 2, 3, 3, 3 };
var b = a.GetContiguousCounts();
foreach (var x in b)
Console.WriteLine(x);
}
For the simple test case, it outputs 1, 2, 3. For your case 334, 333, 110, 222 (the last value is not 223 as you asked in your question, because you only have 999 elements, not 1000).
erm, how about this, most efficient implementation I can think of.
IEnuemrable<KeyValuePair<T, int>> RepeatCounter<T>(
IEnumerable<T> source,
IEqualityComparer<T> comparer = null)
{
var e = source.GetEnumerator();
if (!e.MoveNext())
{
yield break;
}
comparer = comparer ?? EqualityComparer<T>.Default;
var last = e.Current;
var count = 1;
while (e.MoveNext())
{
if (comparer.Equals(last, e.Current))
{
count++;
continue;
}
yield return new KeyValuePair<T, int>(last, count);
last = e.Current;
count = 1;
}
yield return new KeyValuePair<T, int>(last, count);
}
enumerates the sequence exactly once and only allocates variables when necessary.

Are there any implementations of multiset for .Net?

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

Categories