Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
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 digits of 1211 aloud 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 the look and say sequence.
How the Sequence Works
Algorithm
The algorithm works by:
- Starting with the string "1"
- For each term, counting consecutive identical digits
- Converting each group to "count + digit"
- Repeating for n terms
Example
Following is the code:
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' ]
Step-by-Step Breakdown
Let's trace through how "1211" becomes "111221":
const traceExample = (input) => {
console.log(`Tracing: ${input}`);
let result = '';
let chars = input.split('');
let current = chars[0];
let count = 1;
for (let i = 1; i < chars.length; i++) {
if (chars[i] === current) {
count++;
} else {
console.log(`Found ${count} occurrence(s) of ${current}`);
result += count + current;
current = chars[i];
count = 1;
}
}
// Handle last group
console.log(`Found ${count} occurrence(s) of ${current}`);
result += count + current;
console.log(`Result: ${result}`);
return result;
};
traceExample('1211');
Tracing: 1211 Found 1 occurrence(s) of 1 Found 1 occurrence(s) of 2 Found 2 occurrence(s) of 1 Result: 111221
Conclusion
The look-and-say sequence is generated by reading each term aloud, counting consecutive identical digits. This creates a fascinating mathematical pattern where each term describes the previous one.
