dimanche 30 septembre 2018

Remove duplicate string elements C++

The problem consists of finding all permutations using k out of n digits. I'm able to find all the permutations, but I'm struggling trying to erase duplicates. I can successfully compare and find the duplicates, but erasing them is what I'm struggling to do. I have a feeling I'm missing something simple but I don't know what it is.

Any help would be greatly appreciated. I've been staring at this for a week.

Here is the code that I've got right now.

void getPermutations(int n, int k){
    string str = "";
    for(int i = 0; i < n; i++){//fill string with numbers <= n
        str += to_string(i);//convert numbers to string
    }
    string tempStr = "";
    string outputStr = "";
    do{
        tempStr = str.substr(0, k);
        int compareResult = tempStr.compare(0, k, outputStr, 0, k);
        if(compareResult == 0){
            cout << "| same | ";
            outputStr.erase(k,k);

        }
        outputStr = tempStr;
        cout << outputStr << " ";
    }while(next_permutation(str.begin(), str.end()));
}

Aucun commentaire:

Enregistrer un commentaire