Find distinct count of items in a array

Input: [-3, -2, 0, 3, 4, 5]
Output: 5
There are 5 distinct absolute values
among the elements of this array, i.e.
0, 2, 3, 4 and 5)

Input: [-1, -1, -1, -1, 0, 1, 1, 1, 1]
Output: 2

Input: [-1, -1, -1, -1, 0]
Output: 2

Input: [0, 0, 0]
Output: 1

static void Main(string[] args)
{
int[] arr = { -3, -2, 0, 3, 4, 5 };
List<int> distinctList = new List<int>();

for (int i = 0; i < arr.Length; ++i)
{
if (distinctList != null && !distinctList.Contains(Math.Abs(arr[i])))
{
distinctList.Add(Math.Abs(arr[i]));
}
}
Console.WriteLine($”Distinct count is: {distinctList.Count}”);
Console.ReadKey();
}

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s