Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JavaScript – Right Pascal pattern with the Fibonacci sequence

I’m trying to create a Pascal triangle using the Fibonacci sequence. I´m looking for this output:

0
0 1
0 1 1
0 1 1 2
0 1 1 2 3
0 1 1 2 3 5
0 1 1 2 3 5 8 
0 1 1 2 3 5
0 1 1 2 3
0 1 1 2
0 1 1
0 1
0

This is the code I have written so far. I managed to get the Fibonacci sequence running into a triangle but not the way I want.

function fiboP(n) {
  let string = "";
  let n1 = 0
  let n2 = 1
  for (let i = 1; i <= n; i++) {
    for (let j = 0; j < i; j++) {
      string += n1 + " ";
      next_num = n1 + n2;
      n1 = n2;
      n2 = next_num;
    }
    string += "\n";
  }
  for (let i = 1; i <= n - 1; i++) {
    for (let j = 0; j < n - i; j++) {
      string += n1 + " ";
      next_num = n2 - n1;
      n2 = n1;
      n1 = next_num;
    }
    string += "\n";

  }
  console.log(string)
}


fiboP(5)
Output:
0 
1 1 
2 3 5 
8 13 21 34 
55 89 144 233 377 
610 377 233 144 
89 55 34 
21 13 
8

I would like to understand what I am missing here and if there is a cleaner and simpler way to produce the desired output.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

If you reset your values when you go to next line, you should be able to generate the output you’re looking for

function fiboP(n) {
  let string = "";
  for (let i = 1; i <= n; i++) {
    let n1 = 0
    let n2 = 1
    for (let j = 0; j < i; j++) {
      string += n1 + " ";
      next_num = n1 + n2;
      n1 = n2;
      n2 = next_num;
    }
    string += "\n";
  }
  for (let i = 1; i <= n - 1; i++) {
    let n1 = 0
    let n2 = 1
    for (let j = 0; j < n - i; j++) {
      string += n1 + " ";
      next_num = n2 + n1;
      n2 = n1;
      n1 = next_num;
    }
    string += "\n";

  }
  console.log(string)
}


fiboP(7)

As an improvement i will suggest finding fibonacci sequence once and then just using these values to create this triangle.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading