Home > Web Front-end > JS Tutorial > body text

Generate first n sequence of seeing and speaking numbers in JavaScript

WBOY
Release: 2023-09-15 23:57:02
forward
1297 people have browsed it

在 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, …
Copy after login

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
Copy after login

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

One one, one two, two one which gives us 111221
Copy after login

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));
Copy after login

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;
]
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!