Number pattern in JavaScript


The comprehension of numerical patterns in JavaScript is indispensable for web developers who aspire to elevate the effectiveness and proficiency of their code. This notion encompasses the creation of a sequence of numbers that abides by a designated principle or arrangement, rendering valuable perception into the fundamental mathematical concepts that regulate the function of complicated algorithms. The capacity to generate numerical patterns is an elemental aptitude for web developers who strive to refine their code and enrich the user experience of their web-based applications. In this write-up, we will scrutinize the complexities of generating numerical patterns in JavaScript, scrutinizing the diverse methods and approaches that can be utilized to accomplish this objective.

Problem Statement

The pattern is required to produce a series of numbers in a triangular structure, whereby each row contains an increment of numbers from 1 to the current row number. For instance, when the input parameter is 5, the pattern ought to generate an output that contains five rows of numerals, with each row having some numbers depending on the row number.

Pattern 1

Input −

5

Output −

01
01 02
01 02 03
01 02 03 04
01 02 03 04 05

Approach

To create a number pattern using JavaScript, we need to use nested loops. The outer loop will iterate from 1 to the input number, and the inner loop will iterate from 1 to the current value of the outer loop variable. Within the inner loop, we will concatenate the numbers to form the pattern.

Example

The given code defines a function called getPattern(n) to print a triangular pattern of numbers. It initializes a loop that iterates through each row and creates an empty string variable called row. Within the row loop, another loop iterates through each column in the current row. It converts the column number to a string, pads it with a leading zero if needed, and adds a space after each number. After completing the column loop, the row string is printed. Finally, a constant n is declared and assigned a value of 4, and the getPattern function is called with n as the argument to print the pattern for 4 rows.

function getPattern(n){
   // Loop through each row 
   for (let i = 1; i <= n; i++) { 

      // Create an empty string for the row 
      let row = ""; 

      // Loop through each column in the row 
      for (let j = 1; j <= i; j++) { 
         // Add the column number to the row 
         row += j.toString().padStart(2, "0") + " "; 
      } 
      // Print the row 
      console.log(row); 
   } 
}
 
const n=4;
getPattern(n);

Output

The following is the console output −

01 
01 02 
01 02 03 
01 02 03 04

Pattern 2

Input −

5

Output −

1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5

Approach

To generate the pattern, iterate over the rows from 1 to the desired number of rows. Within each row, iterate from 1 to the current row number and append the current number to the pattern string, followed by a space. Add a newline character after each row is completed. Finally, return the generated pattern.

Example

The generateNumberPyramid function takes a parameter rows to determine the number of rows in the pyramid. It uses nested loops to iterate over each row and column, appending numbers with spaces to an empty pattern string. The outer loop represents the current row number, running from 1 to rows. The inner loop runs from 1 to the current row number, concatenating numbers to the pattern. After each inner loop iteration, a newline character is added. Finally, the pattern string is returned.

function generateNumberPyramid(rows) {
   let pattern = '';
   for (let i = 1; i <= rows; i++) {
      for (let j = 1; j <= i; j++) {
         pattern += j + ' ';
      }
      pattern += '
'; } return pattern; } // Example usage: console.log(generateNumberPyramid(5));

Output

The following is the console output −

1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5

Pattern 3

Input −

4

Output −

1 
2 3 
4 5 6 
7 8 9 10

Approach

To generate the pattern, initialize a variable "num" to 1. Iterate over the rows, incrementing from 1 to the desired number. Within each row, iterate from 1 to the current row number. Append the current number to the pattern string, followed by a space. Increment "num" after each number is added. Add a newline character after each row is completed. Finally, return the generated pattern.

Example

The generateFloydsTriangle function takes a parameter representing the number of rows in the triangle and uses loops to build a pattern. It initializes an empty string pattern and a variable num to track the current number. The outer loop iterates through the rows, while the inner loop iterates up to the current row number. Inside the inner loop, num is concatenated with a space and added to the pattern. After each row, a newline character is added. The function returns the pattern string. An example usage is given, calling the function with an argument of 4.

function generateFloydsTriangle(rows) {
   let pattern = '';
   let num = 1;
   for (let i = 1; i <= rows; i++) {
      for (let j = 1; j <= i; j++) {
         pattern += num + ' ';
         num++;
      }
      pattern += '
'; } return pattern; } // Example usage: console.log(generateFloydsTriangle(4));

Output

The following is the console output −

1 
2 3 
4 5 6 
7 8 9 10

Pattern 4

Input −

5

Output −

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Approach

To generate tjhe pattern using binomial coefficients, iterate over the rows and within each row, iterate up to the current row index. Calculate the binomial coefficient for each position using a factorial function. Append the coefficient to the row string followed by a space. Add a newline character after each row. Finally, return the generated pattern. The factorial function should recursively calculate the factorial by multiplying the number with the factorial of (number - 1), returning 1 as the base case for 0 or 1.

Example

The generatePascalsTriangle function takes a parameter for the number of rows and initializes an empty string pattern. It includes a factorial helper function. The outer loop represents the current row, and within it, a row variable stores the numbers in the current row. The inner loop represents the current column, calculates the binomial coefficient, and adds it to the row string. After each row's inner loop completes, the row string is trimmed, a newline character is added, and it is concatenated to the pattern string. Finally, the pattern string is returned. An example usage is provided, calling generatePascalsTriangle with an argument of 5.

function generatePascalsTriangle(rows) {
   let pattern = '';
   for (let i = 0; i < rows; i++) {
      let row = '';
      for (let j = 0; j <= i; j++) {
         let coef = factorial(i) / (factorial(j) * factorial(i - j));
         row += coef + ' ';
      }
      pattern += row.trim() + '
'; } return pattern; } function factorial(num) { if (num <= 1) { return 1; } return num * factorial(num - 1); } // Example usage: console.log(generatePascalsTriangle(5));

Output

The following is the console output −

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

Conclusion

To summarize, the exploration of number patterns in JavaScript can be both intriguing and intellectually stimulating. By leveraging the mathematical properties of numbers and the flexibility of JavaScript, developers can create visually stunning and complex patterns. The applications of these patterns extend beyond just aesthetics, as they can be used to generate randomized values, facilitate data analysis, and aid in encryption algorithms. Thus, the study of number patterns in JavaScript offers a multitude of possibilities for innovation and problem-solving. By delving deeper into the intricacies of number theory and JavaScript programming, developers can expand their skill sets and push the boundaries of what is possible.

Updated on: 04-Aug-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements