Home  >  Article  >  Web Front-end  >  Generate first n sequence of seeing and speaking numbers in JavaScript

Generate first n sequence of seeing and speaking numbers in JavaScript

WBOY
WBOYforward
2023-09-15 23:57:021278browse

在 JavaScript 中生成前 n 个看和说数字的序列

Question

In mathematics, a "look-and-say" sequence is a sequence of integers that begins as follows -

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

For Once Upon a Time A member generates a member of a sequence, we read out the number of the previous member and count the number of numbers in the same number group.

For example, the next number to 1211 is -

111221

Because if we read the number 1211 out loud, it will be -

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

We need to write a JavaScript function, It accepts a number n and returns the first n items of the "look thelook and say" sequence.

Example

The following is the code-

Live demonstration

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

The following is the console output-

[
   &#39;1&#39;,
   &#39;11&#39;,
   &#39;21&#39;,
   &#39;1211&#39;,
   &#39;111221&#39;,
   &#39;312211&#39;,
   &#39;13112221&#39;,
   &#39;1113213211&#39;,
   &#39;31131211131221&#39;,
   &#39;13211311123113112211&#39;,
   &#39;11131221133112132113212221&#39;,
   &#39;3113112221232112111312211312113211&#39;
]

The above is the detailed content of Generate first n sequence of seeing and speaking numbers in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete