Hi have a C code in which I have a 2D char array as -
names[100][20] //Currently maximum 100 names, each of 19 characters supported
This array gets filled by some logic with names. I keep track of total number of names found actually(it could be less than 100 names) in a variable names_found.
Now I want to remove duplicate names which might be present. What I plan to do is something like.
for(i=0;i<names_found;i++)
{
for(j=i+1;j<names_found;j++)
{
//Then compare(strcmp) each string/name with every other.
//e.g. if there were 4 names the comparisons done would be
//{name[0],name[1]},{name[0],name[2]},{name[0],name[3]}
//{name[1],name[2]} , {name[1],name[3]}
//& {name[2],name[3]}
//And then some more logic to remove duplicate based on result of strcmp results. Don't know what this logic would look like to store the result in place, in same 2D character buffer?
}
}
Is this logic of duplicate word removal, what I am doing correct, functionally?
How can I optimize it for speed.
Any better/faster solution.
This is a simple approach. It assumes that the order of the names isn't important:
for (i = 0; i < names_found; i ++)
{
j = i + 1;
while (j < names_found)
{
if (strcmp(names[i], names[j]) == 0)
{
memmove(names + j, names + (names_found - 1), sizeof(names[0]));
-- names_found;
}
else
++ j;
}
}