user8746916
user8746916

Reputation:

Runlength Encoding Algorithm[Data Compression]

I am trying to implement the algorithm RLE with simple input like:

ddddddddddhhhhhhhhhhhhhhhttttttttttttt

code:

#include<iostream>
#include<fstream>
#include<vector>

using namespace std;

int main() {

    vector<char> read;

    ifstream file;
    file.open("file.txt");

    if (!file) {
        cout << "Unable to open";
    }

    char v;

    while(file>>v) {
        read.push_back(v);
    }

    char x;
    int count=0;

    for(int i=0; i<read.size(); i++) {

        x = read[i];

        if(x != read[++i]) {
          cout << x << "1";
        }

        while(x == read[++i]) {
            count++;
        }
        cout << x << count;

        count = 0;
    }


    return 0;
}

The output I am getting is:

d9d1h12h1t10t1

Please help me with the code.

Update: I have updated the question as I have realized few things.

Plus: This code produced no output, is there anything wrong which I am doing wrong?

char o;
char n; 
int count=0; 

for(int i=0; i<read.size(); i++) { 

   o = read[i]; 
   n = read[++i]; 
while(o == n) { 
      count++; 
} 

   cout << o << count; 

      if(o != n) { 
           cout << o << "1"; 
      } count = 0; 
} 
return 0;

Upvotes: 0

Views: 715

Answers (1)

javidcf
javidcf

Reputation: 59691

This loop:

char x;
int count=0;

for(int i=0; i<read.size(); i++) {

    int j=i;
    x = read[i];

    if(x != read[++j]) {
      cout << x << "1";
    }

    while(x == read[++j]) {
        count++;
    }
    cout << x << count;
}

Has several errors. First, you should use two indices, i and j. i is going through each element of read, but then j is iterating through a subsequence too. What you want is to go through each element only once, and in each case either print or increase the count. However having a for loop and moving the index inside too is not a very good practice, is rather error-prone. Also you have to cout statements that are do not run at the right time (you don't wan to print something on every iteration, only when the character changes). You could do it with a while loop, or using a simpler structure like:

// If there are no characters finish
if (read.empty()) {
    return 0;
}
// Get the first character
char lastChar = read[0];
int count = 1;  //  We have counted one character for now
// Go through each character (note start from 1 instead of 0)
for(int i = 1; i < read.size(); i++) {
    // Get the next char
    char newChar = read[i];
    // If it is different, print the current count and reset the counter
    if (lastChar != newChar) {
        cout << lastChar << count;
        count = 1;
        lastChar = newChar;
    } else {  // Else increase the counter
        count++;
    }
}
// Print the last one
cout << lastChar << count;

return 0;

Upvotes: 1

Related Questions