Reputation: 23
I am trying to write a function that inputs an array_string and finds unique words, then copies them over to unique_array. This is a bit over my head I feel like and need some advice on where to go from here..
void unique140(string str_array[], int array_size, string unique_array[], int&unique_size)
{
int i = 0;
int j = 0;
for(i = 0; i < array_size; i++)
{
for(j = 0; j < unique_size; j++)
if (str_array[i] != unique_array[j])
{unique_array[i];}
if(str_array[i] == unique_array[j]
break;
}
Upvotes: 0
Views: 1336
Reputation: 87957
You're not a million miles away, the loops look good. Now you have to use those loops to make a decision, is the word str_array[i]
present in the unique_array
or not? Now just a minutes thought will tell you that str_array[i]
is present if any one of the equality tests str_array[i] == unique_array[j]
is true. Here's how to code that
for(i = 0; i < array_size; i++)
{
bool in_unique_array = false;
for(j = 0; j < unique_size; j++)
if (str_array[i] == unique_array[j])
in_unique_array = true;
...
}
Next we have to add str_array[i]
to unique_array
if it's not already there. So that's
for(i = 0; i < array_size; i++)
{
bool in_unique_array = false;
for(j = 0; j < unique_size; j++)
if (str_array[i] == unique_array[j])
in_unique_array = true;
if (!in_unique_array)
{
...
}
}
Finally having decided to add the string to unique_array
we have to do that
for(i = 0; i < array_size; i++)
{
bool in_unique_array = false;
for(j = 0; j < unique_size; j++)
if (str_array[i] == unique_array[j])
in_unique_array = true;
if (!in_unique_array)
{
unique_array[unique_size] = str_array[i];
unique_size++;
}
}
Upvotes: 0
Reputation: 2988
Try something like:
void unique140(string str_array[], int array_size,
string unique_array[], int&unique_size)
{
unordered_map<string,int> count;
for(int i=0; i<array_size; i++) {
count[str_array[i]]++;
}
unique_size = 0;
for(auto it=count.begin(); it!=count.end(); ++it) {
if(it->second==1) {
unique_array[unique_size++] = it->first;
}
}
}
use a std::map if you dont have a std::unordered_map.
Upvotes: 1