Home >Web Front-end >JS Tutorial >Generate first n sequence of seeing and speaking numbers in JavaScript
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.
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));
The following is the console output-
[ '1', '11', '21', '1211', '111221', '312211', '13112221', '1113213211', '31131211131221', '13211311123113112211', '11131221133112132113212221', '3113112221232112111312211312113211' ]
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!