0

I'm a new developer and got some questions from a test this week and coundn't find a way to solve this one. Any ideas?

The problem I believe is to sort a Javascript string which you have to convert the letters in a row to a new string which adds the times the letter is reapeated to the string; example:

For the string = 'AAABBBBCCX9999!!!!!!**' it should return string = '3A4B2CX496!2*'

I tried some strings and arrays methods but didn't come close. I'm not in a hurry since the test is gone. But would be fun see it resolved; thanks everyone!

I'm still learning so thank you all for your answers and feedback about how to use stack overflow.

  • 5
    why don't you add in your own attemps? that will help others help you. Since you're embarking down the path of developer (many coffees and stackoverflow searches await you young one) it would be prudent to know how to ask questions here. Have a read of [ask] and [mcve] Good luck in your future tests. Failure to follow guidelines will most likely see your questions downvoted & your questions will get closed. – Umar.H Oct 02 '21 at 19:23
  • 1
    This is "run length encoding". Please add the attempts you made so that we can help you understand your errors. – zero298 Oct 02 '21 at 19:36
  • https://stackoverflow.com/questions/49142549/improve-run-length-encoding-algorithm – Bergi Oct 15 '21 at 01:23

1 Answers1

4

It works by matching on the string for all sequences of consecutive characters, giving you an array of each group of consecutive characters, which are then each mapped to a new string of the group's length and the first character put together (AAA becomes 3A ('AAA'.length + 'AAA'[0])). Then each string is glued back together again with .join('').

const seq = 'AAABBBBCCX9999!!!!!!**'
  .match(/(.)\1*/g).map(s => s.length + s[0]).join('');
  
console.log(seq);
Sammy
  • 201
  • 1
  • 5