Troubleshoot the pattern of Pascal's Triangle

Can someone help me understand what's wrong with my implementation of Pascal's Triangle in JavaScript? I came across a similar thread discussing recursion, but I'm having trouble figuring out the errors in my code. I would appreciate fresh eyes to pinpoint any mistakes or suggest improvements. Thank you!

var pascalTriangle = [[1]];

function generatePascal(num, pascalTriangle) {

  if (num < 2) {
    return pascalTriangle;
  }

  var newRow = [1];
  var lastRow = pascalTriangle[pascalTriangle.length - 1];

  console.log(lastRow);

  for (var i = 1; i < lastRow.length; i++) {
    var sum = lastRow[i] + lastRow[i - 1];
    newRow.push(sum);
  }

  pascalTriangle.push(newRow);

 return generatePascal(num - 1, pascalTriangle);
}

generatePascal(2, pascalTriangle);

Answer №1

It appears that a new array called 'addToNewRow' was mistakenly added.

var pTri = [[1]]

function pascalTriangle(num, pTri) {

  if (num < 2) {
    return pTri;
  }

  var newRow = [1];
  var lastRow = pTri[pTri.length - 1];

  console.log(lastRow)

  for (var i = 1; i < lastRow.length; i++) {
    newRow[i] = lastRow[i] + lastRow[i - 1];
  }
    
  newRow.push(1);

  pTri.push(newRow);

 return pascalTriangle(num - 1, pTri);
}

pascalTriangle(10, pTri)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Difficulty in jQuery's clone() function: cloning an input element without its value

I have successfully implemented jquery's .clone() method, but I'm facing an issue where the value of the previous input field is also getting cloned along with it. How can I prevent this from happening? Below is my code snippet: function addrow ...

Creating a Custom Error Page in SpringBoot

After developing an application with SpringBoot that features webservices and a front-office coded in ReactJs, the default port was set to 8080. To simplify the URL access, I decided to switch this application to port 80 by adding the code snippet below to ...

Toggle Visibility of Elements with Javascript and Html

I've been working on implementing a "Show All / Hide All" feature. Currently, clicking on the text opens the image and text individually. However, I am looking to add a functionality for expanding all divs at once. To see how it currently functions, ...

Creating a hash map with the initial element of an array can lead to a potential null point exception

My code snippet looks like the following: char* talk[516] = {(char*)1}; #define testValue (*(int*)talk[0]) After running this code, I encounter a null pointer exception when trying to execute the following line of code. testValue = 0; Why am I getting ...

What is the best method for retrieving an item from localstorage?

Seeking advice on how to retrieve an item from local storage in next.js without causing a page rerender. Here is the code snippet I am currently using: import { ThemeProvider } from "@material-ui/core"; import { FC, useEffect, useState } from "react"; i ...

Calculating the average of a set of numbers through Array manipulation

Looking to calculate the average of the 8 largest numbers out of 12 in an Excel sheet, using VBA. How can I create an array and select the top 8 numbers to include in my calculation? I am interested in receiving any ideas or guidance on how to approach th ...

Using async await in a React component causes a syntax error

Struggling with setting up a basic react app using hapi.js on the server-side, I am diving into the world of webpack and babel as a newcomer. Here's a glimpse at my React component App.jsx: import React from 'react'; export default class A ...

Having trouble with jQuery after adding more content?

I recently started delving into the world of javascript, incorporating it into my website. Just last week, I came across a script that utilizes jQuery to load extra content onto my page. Initially, everything seemed to be functioning smoothly until I reali ...

invoking a function from two separate pages

I have created a React web app that is supposed to hide the navigation bar on the login page and then display it again after a successful login on all other pages. I achieved this by creating a function in App.js, but the issue arises when trying to call t ...

What is the best way to determine if an item in an array is not empty?

Let's consider an array: arr = [{}, {}, {}, {}] If we want to determine the length of the array by counting only objects that contain at least one property, we can do this: [{}, {name: "Manchester United", odds: 3}, {}, {}] // 1 [{}, {name: "Liver ...

Do you think my approach is foolproof against XSS attacks?

My website has a chat feature and I am wondering if it is protected against XSS attacks. Here is how my method works: To display incoming messages from an AJAX request, I utilize the following jQuery code: $("#message").prepend(req.msg); Although I am a ...

Determine the number of JavaScript functions present on a webpage using JavaScript

Hey there! I'm interested in counting the javascript functions on a specific page and then sending this count via ajax. Do you think it's possible to do this using javascript? What would be the best approach? Thanks in advance! Just to explain f ...

Utilizing multiple criteria to filter through a nested array

I am faced with an array structured as follows const treeObj = [ { id: 1, name: 'Section One', items: [ { id: 1, name: 'Section One Item One' }, { id: 2, name: 'Section One Item Two' }, ...

The input tag loses focus after its value is updated using a class method in Angular 8.x

Currently, I am working on integrating a credit card payment method and formatting its number through specific methods. Here is how it is done: HTML <div class="form-group" *ngFor="let formField of cardFields; let cardFieldIndex = index;"> ...

Leverage the power of rxjs to categorize and organize JSON data within an

I am in need of reformatting my data to work with nested ngFor loops. My desired format is as follows: this.groupedCities = [ { label: 'Germany', value: 'de', items: [ {label: 'Berlin', value: 'Berlin ...

Encasing the app component with a context and encountering the issue: TypeError - (destructured parameter) does not have a defined value

My goal is to wrap all components under the app in a context to provide specific functionalities (as evidenced by my UserContext component). import React, { useState, createContext, useContext } from 'react' const Context = createContext(); exp ...

Experimenting with animating an element through onClick event using JavaScript

I would like to create an animated div using JavaScript that activates on click. <div class="Designs"> <p>Designs</p> <div class="Thumbnails" data-animation="animated pulse"> <a href=" ...

The importance of managing both synchronous and asynchronous processes in Javascript

As I delved into the intricacies of Javascript's asynchronous behavior within its single-threaded environment, I stumbled upon a comment that caught my attention regarding the following code snippet: request(..., function (error, response, body) ...

`Vuejs not displaying pdf file correctly`

I am currently using the Laravel DomPDF wrapper to generate PDF files. However, I am facing an issue where I want to render these generated PDF files with my client-side Vue.js app. I have written code that allows me to view and download the PDF file, but ...

The Javascript code fails to execute after other scripts have been employed

Trying to create an expanding search bar that expands upon button click and collapses when clicking elsewhere on the page. The issue I'm facing is that everything works well initially, but after the second script hides the input field on a click outsi ...