Home > database >  Using javascript decipher a string from aaabccdd to a3b1c2d2?
Using javascript decipher a string from aaabccdd to a3b1c2d2?

Time:06-05

I tried this approach but I was not getting the first element of the string. I tried to convert in the opposite way which was way too easy. But in this one somehow I am missing something. Question is, we need to decipher a string from "aabbcdd" to "a2 b2c1d2"

function check(len, string){
    // var obj = {};
    var new_string = "";
    var count =1;
    //console.log(string);
    for(var i=0; i < string.length; i  ){
        let str = string[i];
        if(string[i]===string[i 1] ){
            count  ;
            new_string = new_string   string[i 1]   count;
        }
        if(string[i]!== string[i-1] && string[i]!== string[i 1] && string[i-1] !==undefined){
            count = 1;
            new_string  = new_string   string[i-1]   count;
        }
        
        
        // console.log(string[i],string[i 1], count)
        
    }
    console.log(new_string);
}

Thank you

CodePudding user response:

You'll need to handle the first character of the string differently than the other characters, and you'll also need to update the string again at the end after you've handled the final character.

Here's a heavily commented example demonstrating how you can do so. If something is unclear, feel free to ask for clarification in a comment.

You might find it useful to reference string iterators on MDN.

TS Playground

// Regular expression used to validate each unit (character) of the string
// in the following function, but we instantiate it once instead of
// every time the function is called
const lowerAlphaCharacterRegex = /^[a-z]$/;

// Validate the expected character
function validate (str) {
  if (!lowerAlphaCharacterRegex.test(str)) throw new Error('Invalid input');
}

function encode (input) {
  let result = '';

  // Get an interator for the string to handle each unit
  const iter = input[Symbol.iterator]();
  // Get the first unit and assign it to the working character state
  let previous = iter.next().value;
  // Validate that it meets the criteria
  validate(previous);
  // Set the intiial count to 1
  let count = 1;

  // Iterate over the remaining units in the string
  for (const char of iter) {
    // Validate that it meets the criteria
    validate(char);

    // Simply update the count and continue to the next loop iteration
    // if the current character is the same as the previous one
    if (char === previous) {
      count  = 1;
      continue;
    }

    // Otherwise...

    // Update the result
    result  = `${previous}${count}`;

    // Update the character state
    previous = char;
    count = 1;
  }

  // Update the result from the remaining state
  result  = `${previous}${count}`;

  return result;
}

const input = 'aabbcdd';
const expected = 'a2b2c1d2';
const actual = encode(input);

console.log({
  actual,
  valid: actual === expected,
});

  • Related