-1

I am trying to make Pascal's Triangle in JavaScript but there are lots of errors. I have know idea why errors are happening but there are some.

Code:

function triangle() {
    this.rows = [[1]];
    this.genRow = function() {
        this.rows.push([]);
        this.rows[this.rows.length-1].push(1);
        for (var i = 0; i < this.rows[this.rows.length-1].length; i++){
            var u = [this.rows[this.rows.length-1][i-1], this.rows[this.rows.length-1][i], this.rows[this.rows.length-1][i+1]];
            var f = function(e) {
                return e != undefined;
            };
            function s() {
                var sum=0;
                for (var index = 0; i < this.legnth; i++){
                    sum =+ this[i];
                }
                return sum;
            }
            u = u.filter(f).s();
            this.rows[this.rows.length-1].push(u);
        }
        this.rows[this.rows.length-1].push(1);
    }
}

var t = new triangle();
t.genRow();
console.log(t.rows);

Thanks.

ElectricShadow
  • 683
  • 4
  • 16

3 Answers3

0

Please try this code,To Pasqual's triangle gone wrong

#include <stdio.h> 
  
int binomialCoeff(int n, int k); 
  
void printPascal(int n) 
{ 
    for (int line = 0; line < n; line++) 
    { 
        for (int i = 0; i <= line; i++) 
            printf("%d ", 
                    binomialCoeff(line, i)); 
        printf("\n"); 
    } 
} 
  
int binomialCoeff(int n, int k) 
{ 
    int res = 1; 
    if (k > n - k) 
    k = n - k; 
    for (int i = 0; i < k; ++i) 
    { 
        res *= (n - i); 
        res /= (i + 1); 
    } 
      
    return res; 
} 
  
int main() 
{ 
    int n = 7; 
    printPascal(n); 
    return 0; 
} 

I hope this code will be useful.

Thank you.

Makwana Prahlad
  • 1,025
  • 5
  • 20
0
const pascalsTriangle = (rows = 1) => {
  let res = [];
  for (let i = 1; i <= rows; i++) {
    if (i == 1) {
      res.push([1]);
    }
    else if (i == 2) {
      res.push([1, 1]);
    }
    else {
      let arr = [1];
      let lastArr = res[i - 2];
      for (let index=0; index<lastArr.length-1; index++) {
        arr.push(lastArr[index] + lastArr[index + 1]);
      }
      arr.push(1);
      res.push(arr);
    }
  }
  return res;
};

This will work perfectly. You can refer it here. https://github.com/omkarsk98/Exercism/blob/master/javascript/pascals-triangle/pascals-triangle.js

Omkar Kulkarni
  • 1,091
  • 10
  • 22
0

Here is an approach in JS.

function getNextLevel(previous) {
  const current = [1];
  for (let i = 1; i < previous.length; i++) {
    current.push(previous[i] + previous[i - 1]);
  }
  current.push(1);
  return current;
}

function pascalTriangle(levels = 1) {
  let currentRow = [1];
  while (levels--) {
    console.log(currentRow.join(" "));
    currentRow = getNextLevel(currentRow);
  }
}

pascalTriangle(10);
vighnesh153
  • 4,354
  • 2
  • 13
  • 27