Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I count the unique numbers in an array without rearranging the array elements?

I am having trouble counting the unique values in an array, and I need to do so without rearranging the array elements.

How can I accomplish this?

like image 553
jarus Avatar asked Mar 05 '09 05:03

jarus


People also ask

How do you count unique elements in an array?

Using sort function() Calculate the length of an array using the length() function that will return an integer value as per the elements in an array. Call the sort function and pass the array and the size of an array as a parameter. Take a temporary variable that will store the count of distinct elements.


2 Answers

If you have .NET 3.5 you can easily achieve this with LINQ via:

int numberOfElements = myArray.Distinct().Count();

Non LINQ:

List<int> uniqueValues = new List<int>();
for(int i = 0; i < myArray.Length; ++i)
{
    if(!uniqueValues.Contains(myArray[i]))
        uniqueValues.Add(myArray[i]);
}
int numberOfElements = uniqueValues.Count;
like image 108
Quintin Robinson Avatar answered Sep 21 '22 18:09

Quintin Robinson


This is a far more efficient non LINQ implementation.

        var array = new int[] { 1, 2, 3, 3, 3, 4 };
        // .Net 3.0 - use Dictionary<int, bool> 
        // .Net 1.1 - use Hashtable 
        var set = new HashSet<int>();
        foreach (var item in array) {
            if (!set.Contains(item)) set.Add(item);
        }
        Console.WriteLine("There are {0} distinct values. ", set.Count);
like image 25
Sam Saffron Avatar answered Sep 19 '22 18:09

Sam Saffron