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
Javascript Program to Generate all rotations of a number
Given an integer n, the task is to generate all the left shift numbers possible. A left shift number is a number that is generated when all the digits of the number are shifted one position to the left and the digit at the first position is shifted to the last.Examples: Input: n = 123 Output: 231 31
2 min read
Number Sequences Generator using HTML CSS and JavaScript
In this article, we are going to implement a number sequence generator based on HTML, CSS, and JavaScript. In this program, we have three different types of sequences: the Fibonacci Series, the Prime Number Series, and the Even Odd Number Series. Preview of final output: Let us have a look at how th
5 min read
JavaScript Program to print Fibonacci Series
The Fibonacci sequence is the integer sequence where the first two terms are 0 and 1. After that, the next term is defined as the sum of the previous two terms. The recurrence relation defines the sequence Fn of Fibonacci numbers:Fn = Fn-1 + Fn-2 with seed values F0 = 0 and F1 = 1Examples:Input : 5
4 min read
JavaScript Generator Reference
JavaScript Generator is used to allow us to define an iterative algorithm by writing a single function whose execution is not continuous.Generator Constructor & Generator ObjectsGenerator() Constructor: A generator constructor is defined as a normal function, but whenever it needs to generate a
2 min read
How to generate a n-digit number using JavaScript?
The task is to generate an n-Digit random number with the help of JavaScript. You can also generate random numbers in the given range using JavaScript. Below are the approaches to generate a n-digit number using JavaScript: Table of Content Using Math.random()Math.random() Method and .substring() Me
2 min read
JavaScript Program to Generate Random Hex Codes of Color
What is hex code? A hex code is a six-digit, three-byte hexadecimal number used to represent colors in HTML, CSS, and SVG. The bytes represent the red, green, and blue components of the color. The hex codes are an integral part of HTML for web design and are a key way of representing colors digital
1 min read
Program to generate a random single digit number
Write a program to generate a random single-digit number. Example 1: 7Example 2: 3 Approach: To solve the problem, follow the below idea: To generate a random single-digit number, we can first generate a random integer and then take apply modulo to get the last digit of that random integer. This las
2 min read
JavaScript Program to Print Nth Non Fibonacci Number
JavaScript program to print the nth non-Fibonacci number. Non-Fibonacci numbers are integers that are not part of the Fibonacci sequence. Below are the approaches to print the Nth non-Fibonacci number: Table of Content Using a LoopUsing RecursionUsing a LoopWe are using a while loop to find the nth
2 min read
Program to generate a random two-digit number
Write a program to generate a random two-digit number. Example 1: 73Example 2: 26 Approach: To solve the problem, follow the below idea: We can generate a random two-digit number by generating a random integer first and then modulo it by 90. Now, after modulo 90 the remainder can be in the range 0 t
2 min read
Javascript Program For Adding 1 To A Number Represented As Linked List
Number is represented in linked list such that each digit corresponds to a node in linked list. Add 1 to it. For example 1999 is represented as (1-> 9-> 9 -> 9) and adding 1 to it should change it to (2->0->0->0) Below are the steps : Reverse given linked list. For example, 1->
5 min read