Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a list of non-duplicate numbers in a collection. Can this be done more efficient/shorter code?

Tags:

c#

static IEnumerable<T> FindUniqueNumbersInCollection<T>(ICollection<T> value)
{
    Dictionary<T, byte> hash = new Dictionary<T, byte>();

    foreach (T val in value)
    {
        if (hash.ContainsKey(val)) { hash[val] = 1; continue; }
        hash.Add(val, 0);
    }

    List<T> unique = new List<T>();

    foreach (KeyValuePair<T, byte> kvp in hash)
    {
        if (kvp.Value == 0) unique.Add(kvp.Key);

    }

    return unique;
}
like image 821
Kyle Avatar asked Dec 12 '25 23:12

Kyle


1 Answers

Edit:

I think this is finally correct. :)

var dict = new Dictionary<T, bool>();
foreach (var v in value)
    dict[v] = dict.ContainsKey(v);
foreach (var pair in dict)
    if (!pair.Value)
        yield return pair.Key;  //Algorithmically, as fast as possible

Or if you'd like some LINQ:

var dict = new Dictionary<T, bool>();
foreach (var v in value)
    dict[v] = dict.ContainsKey(v);
return dict.Keys.Where(k => !dict[k]);  //*COULD* be slower on lots of collisions

Or even

var dict = new Dictionary<T, bool>();
foreach (var v in value)
    dict[v] = dict.ContainsKey(v);
return dict.Where(p => !p.Value).Select(p => p.Key); //"Fastest".. but not really

I wouldn't say it's "more efficient" than yours (it's really not -- they're pretty much the same), but it's definitely shorter.


If you want overkill efficiency (at the cost of accuracy), you can always use a Bloom Filter!

like image 91
user541686 Avatar answered Dec 14 '25 13:12

user541686



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!