JavaScript Program to Generate Number Sequence
Last Updated :
18 Jul, 2024
Find the n’th term in the Look-and-say (Or Count and Say) Sequence. The look-and-say sequence is the sequence of the below integers:
1, 11, 21, 1211, 111221, 312211, 13112221, 1113213211
How is the above sequence generated?
n’th term is generated by reading (n-1)’th term.
The first term is "1"
Second term is "11", generated by reading first term as "One 1"
(There is one 1 in previous term)
Third term is "21", generated by reading second term as "Two 1"
Fourth term is "1211", generated by reading third term as "One 2 One 1"
and so on
How to find n’th term?
Example:
Input: n = 3
Output: 21
Input: n = 5
Output: 111221
Number sequence using Iterative Approach
In this approach, we iteratively generate each term of the sequence starting from the base case "1". After which we maintain a current term and use it to generate the next term by counting consecutive digits. The process continues until we reach the nth term.
Example: The below code implements a JavaScript Program to generate a number sequence using an iterative approach.
JavaScript
function countAndSay(n) {
// Base case: the first term is always "1"
let result = "1";
// Iteratively generate each term starting from the second term
for (let i = 1; i < n; i++) {
let temp = "";
let count = 1;
// Iterate through each digit in the current term
for (let j = 1; j < result.length; j++) {
// If the current digit is the same as the
//previous one, increment the count
if (result[j] === result[j - 1]) {
count++;
} else {
temp += count + result[j - 1];
count = 1;
}
}
// Append the count and the last digit
temp += count + result[result.length - 1];
// Update the result to the newly generated term
result = temp;
}
// Return the nth term of the sequence
return result;
}
// Example usage
const n = 5;
console.log("The " + n + "th term of the Count and Say sequence is:
" + countAndSay(n));
OutputThe 5th term of the Count and Say sequence is: 111221
Time Complexity: O(2^N)
Auxiliary Space: O(2^N)
Using Recursive Approach
In the recursive approach, we define a function to generate the nth term of the sequence based on the (n-1)th term. After which we recursively call this function to generate each term until we reach the base case. The base case is when n is 1, in which case we return "1" as the first term of the sequence.
Example: The below code implements a Program to generate a number sequence using a recursive approach.
JavaScript
function countAndSayRecursive(n) {
// Base case: the first term is always "1"
if (n === 1) {
return "1";
}
// Recursive call to generate the
// (n-1)th term of the sequence
const prev = countAndSayRecursive(n - 1);
let temp = "";
let count = 1;
// Iterate through each digit of the (n-1)th term
for (let i = 1; i < prev.length; i++) {
if (prev[i] === prev[i - 1]) {
count++;
} else {
temp += count + prev[i - 1];
count = 1;
}
}
// Append the count and the last digit to the temporary result
temp += count + prev[prev.length - 1];
// Return the newly generated term
return temp;
}
// Example usage
const n = 5;
console.log("The " + n +
"th term of the Count and Say sequence (recursive approach) is: "
+ countAndSayRecursive(n));
OutputThe 5th term of the Count and Say sequence (recursive approach) is: 111221
Time Complexity: O(N*2^N)
Auxiliary Space: O(n)
Using Dynamic Programming Approach
In the dynamic programming approach, we use an array to store the previously computed terms of the sequence. This way, we avoid recalculating the terms multiple times, which helps to optimize the process and reduce time complexity. We generate each term based on the previous term stored in the array and continue this process until we reach the nth term.
Example: The below code implements a JavaScript program to generate a number sequence using a dynamic programming approach.
JavaScript
function countAndSay(n) {
if (n === 1) return "1";
let sequence = ["1"];
for (let i = 1; i < n; i++) {
let prevTerm = sequence[i - 1];
let nextTerm = "";
let count = 1;
for (let j = 1; j < prevTerm.length; j++) {
if (prevTerm[j] === prevTerm[j - 1]) {
count++;
} else {
nextTerm += count + prevTerm[j - 1];
count = 1;
}
}
nextTerm += count + prevTerm[prevTerm.length - 1];
sequence.push(nextTerm);
}
return sequence[n - 1];
}
console.log(countAndSay(3));
console.log(countAndSay(5));
console.log(countAndSay(8));
Output21
111221
1113213211
Time Complexity: O(N*2^N)
Auxiliary Space: O(N*2^N)
Similar Reads
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial
JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development
Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
React Interview Questions and Answers
React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
Steady State Response
In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
JavaScript Interview Questions and Answers
JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial
React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Backpropagation in Neural Network
Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read