Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

c++ - Run length compression only for loop

I am trying to use run length encoding.
Problem is ... a is 2 times But cout show f is 3. A is not showing in result. And last element count var count stay equal to last element.

#include <iostream>

using namespace std;
int main()
{
    string str = "aafffkhjskk";
    int arr[100];
    int count = 1;
    cout << str << endl;
    // print text on screen

    for (int r = 0; r < str.length(); r++) {
        // Str 0 strating point
        for (int in = r; in < str.length(); in++) {
            // r = in because increment finding element
            if (str[r] == str[in]) {
                count++;
            }
            else {
                r += (count - 1);
                // r value is equal to count
                cout << " r " << r << " count " << count << endl;
                cout << count << " ****** "
                     << str[r] << endl;
                count = 1;
                // making count 1 again.
                break;
            }
        }
    } // for end here
}
question from:https://stackoverflow.com/questions/65949449/run-length-compression-only-for-loop

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your select of r (for next starting position) is not right. I suggest using a r_next to mark the next character which is the nearest different character from the current searching one. The a flag pick_next to indicate if r_next is set or not (0 not set, 1 set). The next searching will set to start from r_next:

#include <iostream>
using namespace std;
int main()
{
    string str = "aafffkhjskk";
    int pick_next, r_next, count;
    cout << str << endl;
    int r = 0, count = 0;
    while ((r + count) < str.size()) {
        count = 0; // Str 0 strating point
        pick_next = 0;
        for (int in = r; in < str.length(); in++) {
            // r = in because increment finding element
            if (str[r] == str[in]) {
                count++;
            }
            // mark the first non-identical position
            else {
                if (pick_next == 0) {
                    r_next = in;
                    pick_next = 1;
                }
            }
        }
        cout << "count = " << count << " ****** " << str[r] << endl;
        r = r_next; // place r for next search
    } // end of while
}

Test run:

    $ ./a.exe
    aafffkhjskk
    count = 2 ****** a
    count = 3 ****** f
    count = 3 ****** k
    count = 1 ****** h
    count = 1 ****** j
    count = 1 ****** s
    count = 2 ****** k
--

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...