captain

Can someone give me an algorithm to return distinct values in an array (String)

Re: Visual C# General Help

Thomas Danecker

What do you mean with "distinct values in an array (string)"




Re: Visual C# General Help

boban.s

Create second array of values. Then loop trough your array and for every item check if that item value exists in new array. If don't exists then add it.




Re: Visual C# General Help

Greg Beech

More efficient would be to use a Dictionary<string,anything> to catalog whether you have already seen a string, as this has O(1) lookups rather than O(n) for linear scan in an array. Using a second array would be an O(n^2) algorithm whereas a Dictionary would be O(n). If you need to keep the distinct strings in order then use one of the ordered dictionary variants. Then extract the contents of the dictionary as an array.






Re: Visual C# General Help

Martin Xie - MSFT

Hi Captain,

Here is code sample based on the algorithm that boban.s mentioned.

Code Snippet

static void Main(string[] args)
{
String[] sourceStr = { "121", "1t1", "121","121","11"};
String[] distinctStr ={ "", "", "", "", "" };

int numOfDis=1;
distinctStr[0] = sourceStr[0];
int i, j,count=0;

for (i = 1; i < sourceStr.Length; i++)
{
for (j = 0; j < numOfDis; j++)
{
if (sourceStr[i].Equals(distinctStr[j]))
break;
else
{
//if all existing strings in distinctStr[] don't equal to sourceStr[i], then add sourceStr[i] to distinctStr[].
count++;
if (count == numOfDis)
distinctStr[numOfDis++] = sourceStr[i];
}
}


count = 0;
}

//Get distinct values in the String array
for (i = 0; i < numOfDis; i++)
Console.WriteLine(distinctStr[i]);

Console.ReadLine();

}

The output will be 121 1t1 11.

Hope that can help you!