nida
nida

Reputation: 656

How to display pyramid using JavaScript?

Here is the code to display pyramid but its not exactly producing required output.

function generatePyramid() {
  var totalNumberofRows = 5;
  var arr = new Array();
  for (var i = 1; i <= totalNumberofRows; i++) {
    for (var j = 1; j <= i; j++) {
      arr.push(j);
      console.log(j);
    }
    console.log("\n");
  }
}

Required Output

Upvotes: 8

Views: 169472

Answers (30)

Kamen Kanchev
Kamen Kanchev

Reputation: 49

If you want to create a symmetric pyramid, a great way would be this:

function pyramid(n) {
  let line = "";
  for (let i = 0; i < n; i++) {
    line += " ".repeat(n - i) + "*".repeat(i + (i + 1)) + "\n";
  }
  console.log(line);
}

pyramid(5);

Upvotes: 0

AbdulAhmad Matin
AbdulAhmad Matin

Reputation: 1146

here is another way also in this way we can have repeated values in the side of triangle

let i,j,rows = 5;
var output = `\n`;
for(i=1;i<=rows;i++)
{
  output+= '  '.repeat(rows-i);
  for(j=i;j>=1;j--){
    output+= `${j} `;
  }
  for(j=2;j<=i;j++){
    output+= `${j} `;
  }
  output += '\n';
}
console.log(output);

enter image description here

Upvotes: 0

Devoloper-Rakib
Devoloper-Rakib

Reputation: 11

function strPattern(num) {

    for (var i = 0; i < num; i++) {

        let str = '';

        for (var j = 0; j <= i; j++) {

            str = str + '* ';
        }
        console.log(str);
    }

    for (var i = num - 1; i > 0; i--) {

        let str = '';

        for (var j = 0; j < i; j++) {

            str = str + '* ';
        }
        console.log(str);
    }
}

strPattern(11);

Upvotes: 0

Anand Wadsinge
Anand Wadsinge

Reputation: 31

The most easiest way is:

let ans = [], temp="", n=4;

for (let i=0; i<n; i++) {
  temp += "* ";
  ans.push(temp);
  console.log(temp)
}

Upvotes: 0

Kasem777
Kasem777

Reputation: 865

for(star = "*"; star.length < 8; star += "*"){
     console.log(star);}

Upvotes: -1

Zaid Ahmed Soomro
Zaid Ahmed Soomro

Reputation: 61

  function pyramid(){
        var lines = 5;
        var triangle = "";
        for(var i = 0; i < lines; i++){
            for(var j = i; j < lines; j++) {
                triangle += " "
            }
            for(var j = 0; j <= i; j++) {
                triangle += "X "
            }
            triangle += "<br>"
        }
        console.log(triangle)
    }

Upvotes: 1

mayank
mayank

Reputation: 1

function printNumbers(rows){
  for(let i=1;i<=rows; i++){
   let str='';
   for(let j=1;j<=i; j++){
    str = str + j+' ';
   }
   console.log(str);
  } 
}
printNumbers(5);

Upvotes: 0

Cesar Sarmiento
Cesar Sarmiento

Reputation: 1

function pyramid(n) {
  for (let i = 2; i < n + 2; i++) {
    console.log(" ".repeat(n + 2 - i) + "*".repeat((i - 2) + (i - 1)));
  }
};

pyramid(10);

This is another solution, taking leverage of Fibonacci sequence: 1,3,5,8,13 etc.

Upvotes: 0

Deepanshu
Deepanshu

Reputation: 1

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Pyramid triangle star pattern - javascript</title>
</head>
<body>
  <h2>Pyramid triangle star pattern in javascript</h2>
  <script>
    let n = 5;

    // External loop
    for (let i = 1; i <= n; i++) {
      // printing spaces
      for (let j = n; j > i; j--) {
        document.write('&nbsp;')
      }
      // printing star
      for (let k = 0; k < i * 2 - 1; k++) {
       document.write("*")
      }
    document.write("<br/>")
    }

  </script>
</body>
</html>```

Upvotes: 0

Dibyendu M.
Dibyendu M.

Reputation: 1

function pyramid(row){
    for(var i = 0; i <=row; i++){
        var space="";
        for(let s = 0; s<=(row-i-1); s++){
            space= space+" ";
        }
        var result="";
        for (var j = 1; j <=2*i+1; j++ ){
            result= result+"*"; //result=result+*
        }
        console.log(space+result);
          result="";
    }
   return result;
}
console.log(pyramid(5));

Upvotes: 0

selmetwa
selmetwa

Reputation: 11

my solution.

function pyramid(n) {
// generate base of pyramid, aka longest possible string
let limit = n+n-1;

let hashesToPrint = 1; // number of hashes to print
for (let i=0; i<n; i++) {
    
    // get length of spaces we need on each side
    let difference = (limit - hashesToPrint) / 2;
    
    // generate spaces string
    let spaces = ' '.repeat(difference);

    // create pounds string
    let pounds = '#'.repeat(hashesToPrint);

    // append spaces on either side of our pound string
    let newString = spaces + pounds + spaces

    console.log(newString)

    // increment our counter by two
    hashesToPrint += 2
}

}

pyramid(3)

Upvotes: 0

Horitty TechMasters
Horitty TechMasters

Reputation: 149

One of the Easiest solution is using the .repeat function

let count = 1;
let x = "# ";
for (a = 0; a<=5; a +=1){
    console.log(x.repeat(count));
    count +=1;
}

Upvotes: 3

Pradeep kumar N M
Pradeep kumar N M

Reputation: 145

**You can FRAME for loop conditions for any patterns given either it may be a triangle, right-angled triangle, inverse triangle, etc.. For more info refer the below code and workbook image. PS: in work book image in step 6 it is 2 + i and not 3+i therefore j >= 4 - i && j <= 2 + i for any number of rows n formula is : j >= n+1 - i && j <= n - 1 + i **

EDIT: In Work book image in step 6 it is 2+i and not 3+i therefore j >=4 - i && j <=2 +i for any no. of rows 'n' formula is j > = n + 1 - i && j < = n - 1 + i

1, 3, 5, 7, 9 => Odd number series (stars) appear in pyramid pattern
1, 2, 3, 4, 5 => Counter (number of rows)

For each counter there exist (2 * n) - 1 value

    function pyramid(n) {  // Input or number of rows
        for (var i = 1; i <= n; i++) {
            var s = "";
            // For every each counter there exist 2*n-1 value
            for (var j = 1; j <= (2 * n - 1); j++) {
              // Hint: Check the workbook image
                (j >= n + 1 - i && j <= n - 1 + i) ? s += "*" : s += " ";   
            }
            console.log(s);
        }
    }
    pyramid(5);

enter image description here

For your requirements, the following code should be fine:

    function generateNumberTriangle(v) {
    for (var i = 1; i <= v; i++) {
        var chars = " ";
        for (var j = 1; j <= v; j++) {
            if (j <= i) { chars += j + "  "; }
        }
        console.log(chars);
    }
}
generateNumberTriangle(7);

Upvotes: 7

Shamshirsaz.Navid
Shamshirsaz.Navid

Reputation: 2362

So many inspiring answers; I like to add mine :)

    let m, o, r, c, pr = (n, x = (n << 1) - 1) => {
        m = (x >> 1) << 0;
        o = '';
        for (r = 0; r < n; r++) {
            for (c = 0; c < x; c++)
                o += (m - r <= c && m + r >= c) ? "#" : " ";
            o += '\n';
        }
        console.log(o);
    }

    pr(5);
    pr(20);
    pr(2);

Upvotes: 0

Mehran Rahnama
Mehran Rahnama

Reputation: 11

function pyramid(n){ const midpoint = Math.floor((2 * n-1)/2);

for(let row = 0 ; row < n ; row ++){ let level = '';

 for(let column = 0 ; column < 2*n-1 ; column++)
    {
     if(midpoint-row <= column && midpoint + row >= 
        column){
        level += '#';
       }
       else{
           level += ' ';
           }

    }
   console.log(level);
  }

}

pyramid(5);

Upvotes: 0

Sharmaine Mangombe
Sharmaine Mangombe

Reputation: 1

If you want to print out a right angle triangle using symbols or single digits. You can use the following code.

let pyramid = '';
for(pyramid.length=0; pyramid.length<=7 ; pyramid+='#'){
  console.log(pyramid);
}

Upvotes: 0

Dženis H.
Dženis H.

Reputation: 7822

If we're talking about the 'pyramid' problem, then this would be an appropriate solution.

function pyramid(n) { // If (e.g.) n=3;
  const columnLength = (n * 2) - 1; // 5 
  let middle = Math.floor(columnLength / 2) // middle would be 2
  for(let row=0; row<n; row++) { // let's create the rows (row = horizontal)
    let res = ''; // init our output inside of the 1st for loop
    for(let col=0; col<columnLength; col++) { // creating the columns (column = vertical)
// The following formula would yield the result we need: 
// (n * 2) - 1 => row=2;col=3; row=3;col=5; row=5;col=9
// We got 2 sides, right? 
// So, before we insert '#' we need to make sure the following logic is met:
// Look at:  (middle - row) as being the left side and  (middle + row) as the right one.
// Only if both conditions are met, we want to insert the "#" sign
      if(middle - row <= col && middle + row >= col ) {
         res += '#';
      } else {
// If '#' is NOT inserted then we want to insert something else, right?! 
// In our case that would be an empty string
        res += ' ';
      }
    }
    console.log(res);
  }
}

pyramid(3);


And if we want to be extra 'fancy, we coučld implement recursion:

function recursiveP(n, row=0, res='') { // IMPORTANT: Pass some default values
      const columnLength = (n * 2) - 1;
      let middle = Math.floor(columnLength / 2);
      // This is our EXIT condition, meaning, if have the n number of rows, our work is done!!
      if(n === row) {
        return;
      }
      //  *** Moving on ***
      //   Initially, this will be skipped, and we'll go to the next check and add the appropriate character,
      //   however, after we're finished w/ creating the 1st row we'll hit this check, we'll print the previously generated result,
      //   and call the function again, but this time incrementing the ROW value. This will continue until the 1st check is met
      if(res.length === columnLength) {
         console.log(res);
         return recursiveP(n, row + 1);
      }
      //   Here we're creating the columns and in each, we're inserting the appropriate char
      if(middle - row <= res.length && middle + row >= res.length ) {
         res += '#';
      } else {
         res += ' ';
      }
      //Initial [recursive] function call
      recursiveP(n, row, res);
    }
    
    recursiveP(6);

Upvotes: 0

Spangle
Spangle

Reputation: 822

A fun little solution :)

//set the value of n here      
var n = 5;
generateNumberTriangle(n);

function generateNumberTriangle(n) {
    var width = (2 * n) -1; // Always the case.
    var midpoint = Math.floor(width / 2); // Middle of pyramid.
    let level = ''; // will be reset each level loop

    for(var i = 0; i < n; i++) { // Looping through levels
        level = '';
        for(var j = 0; j < width; j++) {
            if(j < midpoint-i || j > midpoint+i) {
                level += '.';
            } else {
                level += '#';
            }
        }
        console.log(level);
    }
}

Upvotes: 3

Sourabh
Sourabh

Reputation: 694

This will create a proper pyramid in a console:

function createPyramid(rows)
{
    for (let i = 0; i < rows; i++) {
        var output = '';
        for (let j =0; j < rows - i; j++) output += ' ';
        for (let k = 0; k <= i; k++) output += '* ';
        console.log(output);  
    } 
}

createPyramid(5) // pass number as row of pyramid you want.

Upvotes: 11

renuka
renuka

Reputation: 549

Try the below code

function generatePyramid() {
    var totalNumberofRows = 5;
    var output = '';
    for (var i = 1; i <= totalNumberofRows; i++) {
        for (var j = 1; j <= i; j++) {
            output += j + '  ';
        }
        console.log(output);
        output = '';
    }
}

generatePyramid();
   

Upvotes: 18

Darshit
Darshit

Reputation: 85

Shorter way

 function generatePyramid(n) {
        var output="";
        for (var i = 1; i <= n; i++) {
            output += i + " ";
            console.log(output);
        }
    }  

    generatePyramid(5);

Upvotes: 0

Jordan Stubblefield
Jordan Stubblefield

Reputation: 523

Assuming you want to return numbers and not asterisks as the other answers show, here is that solution:

Note that this solution runs in linear (O(n)) time complexity and doesn't sacrifice performance by logging every line to the console, but the entire pyramid at once instead.

function generatePyramid(n) {
  let pyramid = '';
  let prev;

  for (let i = 1; i <= n; i++) {
    if (prev) {
      pyramid += '\n';
      prev =  prev + ' ' + i;
    } else {
      prev = i;
    }
    pyramid += ' '.repeat(n - i) + prev;
  }

  return pyramid;
}

Log to the console as such: console.log(generatePyramid(n));

If you're looking to just draw a triangle as the picture in your question shows, this function will do that (again, in linear time complexity):

function drawTriangle(n) {
  let triangle = '';
  let prev;
  for (let i = 1; i <= n; i++) {
    if (prev) {
      triangle += '\n';
      prev = prev + ' ' + i;
    } else {
      prev = i;
    }
    triangle += prev;
  }
  return triangle;
}

Upvotes: 0

Sagar Kharche
Sagar Kharche

Reputation: 2681

The easiest solution is:-

function pyramid(n) {

 

  for(let i=1; i<= n; i++){

    let str = ' '.repeat(n-i);

    let str2 = '*'. repeat(i*2 -1)

 

    console.log(str + str2 + str);

  }

}

pyramid(5);

Upvotes: 14

Benjamin Livinus
Benjamin Livinus

Reputation: 39

To draw a pyramid on the console using JavaScript

  1. Make each line have an odd number of fill characters.
  2. Prepend spaces (or 'spacer characters') before each line, excluding the last.
    To do this:
    • Use repeat() to determine the number of spacer characters for each line. You do that by passing the number of lines - 1 as an argument.

Here's my solution

function drawPyramid(lines, fillChar, spacerChar) {
  let fillChars = '';
  let spacer = spacerChar || ' '; // Default spacer is ' '
  let spacerCount = lines;

  for (let i = 1; i <= lines; i++) {
      fillChars += fillChar;

  // Makes lines always have an odd number of fill characters
    if (i >= 2)
        fillChars = fillChar + fillChars;

    console.log(spacer.repeat(spacerCount - 1) + fillChars);
    spacerCount--;
  }
}

drawPyramid(4, '*');

Upvotes: 1

Svyatoslav Gerasimov
Svyatoslav Gerasimov

Reputation: 140

I would stick to recursive approach in such a case:

function generatePyramid (n, row = 0, line = '', number = 1) {
  
    if(row === n){
      return;
    }
    
    if (line.length === n) {
        console.log(line )
        return generatePyramid (n, row + 1)
    } 
    
    if (line.length <= row) {
        line += number;
    } else {
        line += ' ';
    }
    
    generatePyramid (n, row, line, number + 1)
  }

Upvotes: 0

Gajender Singh
Gajender Singh

Reputation: 1313

function pyramid() {
    var n = 5;
    var output="";
    for (var i = 0; i <n; i++) {
    var myspace = "";   
    for(let s = 0; s <(n-i-1); s++) {
        myspace += " ";
    }
        for (var j = 1; j <= 2*i + 1; j++) {
            output+="*";

        }
        console.log(myspace+output);
        output="";
    }
}

Output

            *
VM74:11    ***
VM74:11   *****
VM74:11  *******
VM74:11 ********* 

Upvotes: 0

Lior Elrom
Lior Elrom

Reputation: 20882

Another Option

One line of code:

function generatePyramid(n) {
    return [...Array(n)]
        .forEach((_, i) => console.log([...Array(++i)].map((_, j) => ++j).join(' ')));
}

Upvotes: 2

Jaydeep
Jaydeep

Reputation: 39

Simple code of Number Pyramid

for(var i=1; i<=5; i++){
 var Num='';
 for(var j=0; j<i; j++){
     Num += i;
 }
 print(Num) }

Upvotes: 1

Kunle Babatunde
Kunle Babatunde

Reputation: 19

  const pyramid = (n)=>{
  const mid = Math.floor((2*n-1)/2);
  for(let row=0; row<n; ++row)
  {
    //for each row, make empty steps
    let level = ''
    for(let col=0; col<2*n-1; col++)
    {
      if(mid-row <=col && mid+row >= col)
        level+='#';
      else level +=' ';
    }
    console.log(level);
  }
}
pyramid(3);

Upvotes: 1

Scott Campbell
Scott Campbell

Reputation: 21

Here's a simple solution using ES6 syntax

function generatePyramid(num) {
  let number = '';

  for (let i = 1; i <= num; i++) {
    console.log(number += i);
  }
}
generatePyramid(5);

Upvotes: 2

Related Questions