how to build count and say problem in javascript

Viewed 722

I am trying to solve the below problem in JavaScript

The count-and-say sequence is the sequence of integers beginning as follows:

1, 11, 21, 1211, 111221, ...
1 is read off as one 1 or 11.
11 is read off as two 1s or 21.

21 is read off as one 2, then one 1 or 1211.

Given an integer n, generate the nth sequence.

Note: The sequence of integers will be represented as a string.

Example:

if n = 2,
the sequence is 11.

So I want to create a function which pass N integer and gives it value

Here is my code:

let countAndSay = function (A) {
    if (A == 1) return "1"
    if (A == 2) return "11"
    let str ="11"
    if(A > 2){
     // count 
    }
}

I don't understand the logic for how to build this.

2 Answers

You need to be able to dynamically determine the number and type of chunks a string has, which can be done pretty concisely with a regular expression. To come up with the string to deconstruct on index n, recursively call countAndSay to get the result of n - 1:

let countAndSay = function (count) {
  if (count === 1) {
    return '1';
  }
  const digitsArr = countAndSay(count - 1).match(/(\d)\1*/g);
  // You now have an array of each chunk to construct
  // eg, from 1211, you get
  // ['1', '2', '11']
  return digitsArr // Turn the above into ['11', '12', '21']:
    .map(digitStr => digitStr.length + digitStr[0])
    .join(''); // Turn the above into '111221'
};
console.log(
  countAndSay(1),
  countAndSay(2),
  countAndSay(3),
  countAndSay(4),
  countAndSay(5),
);

Here's a function that generates the next string of numbers based on the previous string you feed it:

function next(s) {
    s = s + "*";  // add a flag value at the end of the string
    var output = "";
    var j = 0;
    for (var i = 1; i < s.length; i++) {
        if (s.charAt(i) != s.charAt(i - 1)) { // if the character changes, concatenate the amount (i - j) and the digit
            output += (i - j) + s.substring(j, j+1);
            j = i;
        }
    }
    return output;
}

Then you'd need to recursively run next N times.

Related