DEV Community

Bukunmi Odugbesan
Bukunmi Odugbesan

Posted on

Coding Challenge Practice - Question 69

The task is to create a function to return the n-th number string in a sequence. n starts from 1.

The boilerplate code

function getNthNum(n) {
  // your code here
}
Enter fullscreen mode Exit fullscreen mode

Start with the first number

if(n === 1) return "1";
Enter fullscreen mode Exit fullscreen mode

To get the next number, describe the digits of the previous ones. Count how many times the same digits appear one after the other. When it changes to a new digit, write the count down and the digit being counted.

let result = "1";

  for (let i = 2; i <= n; i++) {
    let current = "";
    let count = 1;

    for (let j = 1; j <= result.length; j++) {
      if (result[j] === result[j - 1]) {
        count++;
      } else {
        current += count.toString() + result[j - 1]; 
        count = 1;
      }
    }

    result = current;
  }
Enter fullscreen mode Exit fullscreen mode

After repeating the process n times, return the final string.

return result
Enter fullscreen mode Exit fullscreen mode

The final code:

function getNthNum(n) {
  // your code here
  if(n === 1) return "1";

  let result = "1";

  for(let i = 2; i <= n; i++) {
    let current = "";
    let count = 1;

    for(let j = 1; j <= result.length; j++) {
      if(result[j] === result[j - 1]) {
        count++
      } else {
        current += count.toString() + result[j - 1];
        count = 1;
      }
    }
    result = current;
  }
  return result;
}
Enter fullscreen mode Exit fullscreen mode

That's all folks!

Top comments (0)