Cizel
Cizel

Reputation: 69

Shifting unique values to the left and removing duplicated values in a string

I am trying to write a function that takes the unique values in a string, shifts them all together to the left and then set the duplicated values as an empty string. I wanted my function to return how many values were changed into an empty string.

My array is { "cindy" , "sasha" , "cindy" , "daisy" , "bear" , "bear" , "bear" }; but the code I have seems to be skipping over the "bear" once and only returning 2.

for example, I can't do it like this

int duplicaterase(string array[], int  n)
{
const auto end = array + n;
auto finish = end;
for (auto start = array; start != finish; ++start) {
    finish = std::remove(start+1, finish, *start);
}
std::fill(finish, end, std::string());
return static_cast<int>(end - finish);;
}

Upvotes: 2

Views: 75

Answers (3)

Maarten Hilferink
Maarten Hilferink

Reputation: 723

After removing the 2nd bear from position 4, the 3rd bear moved to that position and then you continue to look for bears from position 5 onward and you missed it. Try replacing the last if by while to continue removing bears before incrementing j.

Upvotes: 0

Jive Dadson
Jive Dadson

Reputation: 17026

Following up on Jonathan Mee's answer, this is a C++ way of doing it.

#include <algorithm>
int removeDuplicatedValues(string array[], int  n)
{
    const auto end = array + n;
    auto finish = end;
    for (auto start = array; start != finish; ++start) {
        finish = std::remove(start+1, finish, *start);
    }
    std::fill(finish, end, std::string());
    return static_cast<int>(end - finish);;
}

Upvotes: 3

Jonathan Mee
Jonathan Mee

Reputation: 38919

This can be simply accomplished using remove in a for-loop:

auto finish = end(duplicates1);

for(auto start = begin(duplicates1); start != finish; ++start) finish = remove(next(start), finish, *start);
fill(finish, end(duplicates1), string());

Live Example


The above solution preserves order, but truly the fastest solution would be to sort and use unique:

sort(begin(duplicates1), end(duplicates1));
fill(unique(begin(duplicates1), end(duplicates1)), end(duplicates1), string());

Live Example

Upvotes: 3

Related Questions