samin saju
samin saju

Reputation: 23

Write a program the compress the string

Question: Run-length encoding (RLE) is a simple "compression algorithm" (an algorithm which takes a block of data and reduces its size, producing a block that contains the same information in less space). It works by replacing repetitive sequences of identical data items with short "tokens" that represent entire sequences. Applying RLE to a string involves finding sequences in the string where the same character repeats. Each such sequence should be replaced by a "token" consisting of:

the number of characters in the sequence
the repeating character

If a character does not repeat, it should be left alone.

For example, consider the following string:

qwwwwwwwwweeeeerrtyyyyyqqqqwEErTTT

After applying the RLE algorithm, this string is converted into:

q9w5e2rt5y4qw2Er3T

This is what I have so far, I don't know how to count the characters like how many times a character is repeated. Can someone please help!!!!

public class Compress1 {
    public static void main(String[] args){
        System.out.println("Enter a string");
        String input = IO.readString();
        char[] inputChar = input.toCharArray();
        for (int index = 0; index < inputChar.length; index++){
            char current = inputChar[index];

            if (current == (current + 1)){
                int count = 
            }
        }
    }
}

Upvotes: 2

Views: 5508

Answers (4)

Bohemian
Bohemian

Reputation: 424973

Rather than debug your code, here's some working code:

String input = "qwwwwwwwwweeeeerrtyyyyyqqqqwEErTTT";

String previous = input.substring(0, 1);
int count = 1;
for (String c : input.substring(1).split("")) {
    if (previous.equals(c)) {
        count++;
    } else {
        System.out.print((count == 1 ? "" : count) + previous);
        previous = c;
        count = 1;
    }
}
System.out.println((count == 1 ? "" : count) + previous);

Output:

q9w5e2rt5y4qw2Er3T

Compare it with your own and follow its logic to find out where you went wrong.

Upvotes: 2

Igor Tyulkanov
Igor Tyulkanov

Reputation: 5548

public static void main (String[] args) {
    System.out.println("Enter a string");
    String input = IO.readString();
    final char[] charArray = input.toCharArray();
    final StringBuilder stringBuilder = new StringBuilder();
    int index = 1;
    for (int current = 1, previous = 0; current <= charArray.length; current++, previous++) {
        if (current == charArray.length || charArray[previous] != charArray[current]) {
            if (index > 1) {
                stringBuilder.append(index);
            }
            stringBuilder.append(charArray[previous]);
            index = 1;
        } else {
            index++;
        }
    }
    System.out.println(stringBuilder.toString());
}

Upvotes: 0

Saravana
Saravana

Reputation: 12817

You can try this:

String str = "qwwwwwwwwweeeeerrtyyyyyqqqqwEErTTT";
char[] arr = str.toCharArray();
int count = 1;
StringBuilder sb = new StringBuilder();
char prev = arr[0];

for (int i = 1; i < arr.length; i++) {
    char curr = arr[i];
    prev = arr[i - 1];
    if (curr == prev) {
        count++;
    } else {
        if (count < 2) {
            sb.append(prev);
        } else {
            sb.append(count).append(prev);
            count = 1;
        }
    }
}

if (count < 2) {
    sb.append(prev);
} else {
    sb.append(count).append(prev);
}

System.out.println("Compressed : " + sb.toString());

output : Compressed : q9w5e2rt5y4qw2Er3T

Upvotes: 1

Tim Biegeleisen
Tim Biegeleisen

Reputation: 520888

Here is a working version of your code. It walks along an input string character by character. If the next character be different than the preceding one, then it prints RLE version of the character (i.e. just the character if it occurred only once, or a number followed by the character in case it occurred more than once). If the next character be the same as the preceding one, then it increments a counter to keep track of the number of occurrences.

If you look closely, you will notice that I append a new line (\n) to the end of the input string. This allows my algorithm to "know" that it has hit the end of the input string. And it also will nicely print a newline in the event that you plan to input multiple strings for RLE processing.

At some point, you may want to extract out a method which does the RLE processing. For now, I have left the code as is inside your main() method.

public class Compress1 {
    public static void main(String[] args){
        System.out.println("Enter a string");
        String input = IO.readString();

        // check for null or empty input
        if (input == null || input.length() == 0) {
            System.out.println("null or empty string input");
            System.exit(0);
        }

        // handle single character input
        if (input.length() == 1) {
            System.out.println(String.valueOf(curr));
            System.exit(0);
        }

        // add a newline character to the end of the input string
        // so the algorithm can detect a "change" at the end
        input += "\n";

        char curr = input.charAt(0);
        int count=1;

        for (int i=1; i < input.length(); ++i) {
            char next = input.charAt(i);
            if (curr != next) {
                if (count > 1) {
                    System.out.print(count + String.valueOf(curr));
                }
                else {
                    System.out.print(curr);
                }
                count = 1;
            }
            else {
                ++count;
            }

            curr = next;
        }
    }
}

Here is a sample input and output which I tested using IntelliJ:

Input:

qwwwwwwwwweeeeerrtyyyyyqqqqwEErTTT

Output:

q9w5e2rt5y4qw2Er3T

Upvotes: 0

Related Questions