Skip to content

Pascal Triangle

Intro

In Pascal's Triangle each number is computed by adding the numbers to the right and left of the current position in the previous row.

1
2
3
4
5
6
    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1
# ... etc

Task

Compute Pascal's triangle up to a given number of rows.

The Code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include "pascals_triangle.h"
#include <vector>

namespace pascals_triangle {
const std::vector<std::vector<int>> generate_rows(int test) {
std::vector<std::vector<int>> var{};
var.resize(test);
if (test == 0)
    return var;
for (int i = 0; i < test; i++) {
    for (int ii = 0; ii <= i; ii++) {
    if (ii == 0) {
        var[i].push_back(1);
        continue;
    }
    if (ii == i) {
        var[i].push_back(1);
        continue;
    }
    var[i].push_back(var[i - 1][ii - 1] + var[i - 1][ii]);
    }
}
return var;
}
} // namespace pascals_triangle
1
2
3
4
5
6
7
8
9
#include <vector>
#if !defined(PASCALS_TRIANGLE_H)
#define PASCALS_TRIANGLE_H

namespace pascals_triangle {
const std::vector<std::vector<int>> generate_rows(int);
} // namespace pascals_triangle

#endif // PASCALS_TRIANGLE_H

Last update: February 13, 2021

Comments