Generating the sequence of first n look and say numbers in JavaScript


Problem

In mathematics, the look-and-say sequence is the sequence of integers beginning as follows −

1, 11, 21, 1211, 111221, 312211, …

To generate a member of the sequence from the previous member, we read off the digits of the previous member, counting the number of digits in groups of the same digit.

For instance, the next number to 1211 is −

111221

Because if we read the digit of 1211 louder it will be −

One one, one two, two one which gives us 111221

We are required to write a JavaScript function that takes in a number n and returns the first n terms of look the look and say sequence.

Example

Following is the code −

 Live Demo

const num = 12;
const generateSequence = (num = 1) => {
   const lookAndSay = (val) => {
      let res = '';
      let chars = (val + ' ').split('');
      let last = chars[0];
      let count = 0;
      chars.forEach(c => {
         if(c === last){
            count++;
         }else{
            res += (count + '') + last;
            last = c;
            count = 1;
         };
      });
      return res;
   }
   let start = 1;
   const res = [];
   for(let i = 0; i < num; i++){
      res.push(String(start));
      start = lookAndSay(start);
   };
   return res;
};
console.log(generateSequence(num));

Output

Following is the console output −

[
   '1',
   '11',
   '21',
   '1211',
   '111221',
   '312211',
   '13112221',
   '1113213211',
   '31131211131221',
   '13211311123113112211',
   '11131221133112132113212221',
   '3113112221232112111312211312113211'
]

Updated on: 20-Apr-2021

311 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements