Compression String does not work for all strings

Viewed 55

The idea is to complete the function and produce a compressed form of the string given. An example would be if the given string was aabbcc then you would get a2b2c2

The issue with the code I created is for some reason it does not work with anything right away that is consecutive or consecutive letters at the end. wwww turns into w4 but aa does not turn into a2 and wuenuneubgnjfniwfibwiebfaaa will not turn into wuenuneubgnjfniwfibwiebfa3

function compressedString(message) {
  let out = '';
  let count = 1;

  for (let i = 0; i < message.length; i++) {
    let current = message[i];
    let next = message[i + 1];
    if (current == next) {
      count++;
    } else {
      out += current + String(count);
      count = 1;
    }
  }
}
2 Answers

I test your algorithm, using given example of your question wuenuneubgnjfniwfibwiebfaaa, the output was w1u1e1n1u1n1e1u1b1g1n1j1f1n1i1w1f1i1b1w1i1e1b1f1a3, what sounds strange for the string compression requirement. When I add a nested condition inner first else in for loop, I acquired the correct result, please view the code bellow and let what do you think about:

 function compressedString(message) {
  let out = '';
  let count = 1;

  for (let i = 0; i < message.length; i++) {
    let current = message[i];
    let next = message[i + 1];
    if (current == next) {
      count++;
    } else {
      if(count == 1){
        out += current;
      }else{
        out += current + String(count);
      }
      count = 1;
    }
  }
 return out;
}

Your issue is the way you are handling it in the end. What happens to the variable next when the loop is on the last iteration? You need to add an extra check on your if.

Try this:

function compressedString(message) {
  let out = '';
  let count = 1;
  
  for (var i = 0; i < message.length; i++){
    let current = message[i];
    let next = message[i + 1];
    if ( i < message.length-1 && message[i] == next) {
      count += 1;
    } else {
      out += current + String(count);
      count = 1; 
    }
  }
  return out;
}
Related