5

My for loop for my string compression is a bit off. I have been working on this assignment the past 5 days and I can't figure out for the life of me what is wrong. Can someone help me out?

For example, I passed over the string "TTTTrrrEe" and instead of getting T4r3Ee, I'm getting T4r3EeTT. I don't know why it jumps back to the beginning of the string like that, but I am getting closer.We can only use charAt,equals,length, and substring from the string class.

Can someone help guide me in the right direction by helping to correct my logic? I still want to try and code this myself, seeing as how it is an assignment.

public static String compress(String s){
    int count = 0;
    String temp = s.substring(0,1);
    for(int i = 0; i < s.length(); i++){
        if(i !=s.length()-1){
            if(temp.equals(s.substring(i,i+1))){
                count++;

            }else{

                if(count < 1){
                    System.out.print(s.substring(i,i+2));
                    System.out.print(temp.substring(0,1) );
                }else{
                    System.out.print("" + temp.substring(0,1) + count);
                    i--;
                    temp = s.substring(count,count+1);
                    System.out.println(" temp is now " + temp);

                    count = 0;
                    //i--;
                }
            }
        }

    }

    System.out.println(temp);

    return temp;
}
4
  • 4
    Why don't you loop through the String and check the character by String.charAt(i) instead of subString(). It will make your life easy. Commented Sep 11, 2013 at 13:35
  • As general programming practice, try to avoid deep nesting. For example, if(i != s.length() - 1){//loop body}, try if(i == s.length()-1){continue;}//loop body Commented Sep 11, 2013 at 13:38
  • Is the assignment ignoring the fact that this is an ambiguous compression algorithm, unless your string cannot contain numbers? Commented Sep 11, 2013 at 13:43
  • There is no need to include java in the question title if you already included it as a tag. Also the "help needed" in the question is unnecessary since it is obvious that you need help from the fact that you are posting a question. Commented Sep 11, 2013 at 13:52

6 Answers 6

3

Since this is a learning exercise, I wouldn't try fixing your code, just point out a few things to work on to get it right:

  • The if (i !=s.length()-1) condition inside the loop becomes unnecessary if you change your for loop condition to i < s.length()-1
  • Comparing individual characters is easier (and faster) than comparing substrings. You get a character at position i by calling char ch1 = s.charAt(i), and compare two characters using == operator, rather than calling equals() on them.
  • When count is zero (your count < 1 condition is equivalent to count == 0) you print both the current character and the character after it, in addition to the first character of temp followed by the count. This does not look correct.
  • Rather than growing temp as you go through the loop, you set it on each iteration. This does not look correct.
  • A better way of growing temp as you go through the loop is using StringBuilder and append(), instead of using a plain String, and performing concatenations.
Sign up to request clarification or add additional context in comments.

1 Comment

I would probably use an inner loop on the same variable as the outer loop. Then you can fix a character easily for the inner loop
0

Try using some logic like this;

int count = 0;
for(int i =0; i < string.length()-1; i++){
    if(string.charAt(i) == string.charAt(i + 1)){
        count++;
        // DO SOME OPERATION
    }
}

1 Comment

Yes, I just planned to give the sketch, so that the OP could solve it using the logic. Did not want to give the entire solution.
0

temp = s.substring(count,count+1); does not relate to a position (i), but a size.

In fact I would try to rewrite it afresh, with externally sensible names:

char repeatedChar = `\u0000`; // Not present.
int repetitions = 0;

Because of the no-namer count you got into trouble.

Comments

0

Working code:

public  class HelloWorld  {

public static void compress(String s){

    StringBuilder buff = new StringBuilder();

    char tmp = '\0';

    int index = 1;

    for(int i = 0; i < s.length(); i++){

        char curr = s.charAt(i);            

        if(buff.length() == 0){             
            tmp = curr;
            buff.append(tmp);
            continue;
        }           

        if(curr == tmp){
            index++;
        }
        else{                   
            if(index > 1){
                buff.append(index);
                index = 1;
                tmp = curr;
            }

            buff.append(curr);              
        }


    }

    System.out.println(buff.toString());

}


public static void main(String args[]){
    compress("TTTTrrrEe");
}
 }

Output: T4r3Ee

For compress("TTsssssssssssTTrrrEe");

Output: T2s11T2r3Ee

Comments

0

String temp = s.substring(0,1);

temp.equals(s.substring(i,i+1))

In case of these 2 sentences you should have used a char instead of String, as such:

char temp = s.charAt(0)

temp == s.charAt(i)

I would start with 3 variables:

char lastCharacter = inputString.charAt(0); int count = 1; String result = "";

then proceed to process the input string in a loop:

if (length <= 1) return inputString;
for i = 1 ; i < length;i++
    if (inputString.charAt(i) == lastCharacter && i != length-1)
        count++
    else
        if count == 1 
            result += lastCharacter
        else 
            result = result + lastCharacter + count;
            count = 1;
        end if
        lastCharacter = inputString.charAt(i);
    end if
end for
return result;

Comments

0

TRY THIS

    public class Compress {

        /**
         * @param args
         * @author Rakesh KR
         */
         public static String encode(String source) {
                StringBuffer dest = new StringBuffer();
                for (int i = 0; i < source.length(); i++) {
                    int runLength = 1;
                    while (i+1 < source.length() && source.charAt(i) == source.charAt(i+1)) {
                        runLength++;
                        i++;
                    }
                    dest.append(source.charAt(i));
                    dest.append(runLength);
                }
                return dest.toString();
            }

        public static void main(String[] args) {
            // TODO Auto-generated method stub
            String example = "aaaaaaBBBBccc";
            System.out.println("Encode::"+encode(example));
        }

    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.