DEV Community

Santiago Salazar Pavajeau
Santiago Salazar Pavajeau

Posted on

Count and say 1️⃣2️⃣3️⃣...

This problem asks to write a program that translates a number between 1 and 30 to count and say. This means that starting with 1, we need to find the next number which is the count of any consecutive duplicate integers and the number itself. So we use the last number to find the next. Let me try to explain it more visually:

  1. 1
  2. 11
  3. 21
  4. 1211
  5. 111221
  6. 312211
  7. 13112221
  8. 1113213211
  9. 31131211131221
  10. 13211311123113112211

Since 4 is 1211, 5 is 111221 so digit by digit:

  • 1 -> 11 (one ones)
  • 2 -> 12 (one twos) so far: 1112
  • 11 -> 21 (two ones) final: 111221

Code

Taking a look at the algorithm:

let countAndSay = (n) => {

    let result = '1'

    for(let i = 1; i < n ; i++){

        let consecutiveDigits = ''
        let substringResult = ''

        for(let j = 0; j < result.length; j++){

            consecutiveDigits += result[j]

                if(result[j] !== result[j+1]){

                    substringResult += `${sameDigits.length}${sameDigits[0]}`
                    consecutiveDigits = ''
                }
        }
        result = substringResult
    }
    return result
};
Enter fullscreen mode Exit fullscreen mode

We start the count at 1 as a string (let result = '1'), then set an empty string that will track the consecutive digits (let consecutiveDigits = '') and if there are duplicates we add them (consecutiveDigits += result[j]).

When the next number is different (if(result[j] !== result[j+1])) we count the current duplicates (consecutiveDigits.length) and add the current number (consecutiveDigits[0]).

Both values are added as substrings in the inner loop (substringResult) and this is set to result on the outer loop.

After the inner loop iteration is finished we set the result variable to the substrings we have collected.

The outer loop goes on until we reach the desired number to translate to count and say and stores the previous number. While the inner loop goes analyses the previous count and say number to generate the next number.

Feel more than welcome to reach out or connect!

Top comments (0)