the-honk/languages/c++/code/pascal.cc

79 lines
1.7 KiB
C++
Raw Normal View History

#include <iostream>
#include <vector>
using namespace std;
// Calculate Pascal's triangle
2024-10-09 17:02:42 +00:00
vector<vector<long long>> pascal(int rowCount) {
vector<vector<long long>> rows{{1}};
for (int i = 0; i < rowCount; i++) {
2024-10-09 17:02:42 +00:00
vector<long long> previousRow = rows[rows.size() - 1];
vector<long long> newRow{1};
for (int j = 0; j < previousRow.size() - 1; j++) {
newRow.push_back(previousRow[j] + previousRow[j + 1]);
}
newRow.push_back(1);
rows.push_back(newRow);
}
return rows;
}
2024-10-09 17:02:42 +00:00
// Find the length of a vector if it were outputted as a string with a space between each value
int vectorStringLength(vector<long long> vector) {
int value = vector.size();
for (int i = 0; i < vector.size(); i++) {
value += to_string(vector[i]).size();
}
return value;
}
2024-10-09 17:02:42 +00:00
// Draw Pascal's Triangle
void drawPascalTriangle(int rowCount) {
vector<vector<long long>> pascalsTriangle = pascal(rowCount);
int bottomRowSize = vectorStringLength(pascalsTriangle[pascalsTriangle.size() - 1]);
2024-10-09 17:02:42 +00:00
for (int i = 0; i < pascalsTriangle.size() - 1; i++) {
vector<long long> currentRow = pascalsTriangle[i];
int rowSize = vectorStringLength(currentRow);
2024-10-09 17:02:42 +00:00
int sizeDifference = bottomRowSize - rowSize;
2024-10-09 17:02:42 +00:00
string spacing = "";
for (int j = 0; j < sizeDifference / 2; j++) {
spacing += " ";
}
for (int j = 0; j < currentRow.size(); j++) {
if (j == 0) {
cout << spacing;
}
cout << to_string(currentRow[j]) + " ";
if (j == currentRow.size() - 1) {
cout << spacing;
}
}
if (i != pascalsTriangle.size() - 1) {
cout << endl;
}
}
}
2024-10-09 17:02:42 +00:00
int main() {
cout << "How many rows of Pascal's Triangle would you like to calculate? ";
int rowCount;
cin >> rowCount;
drawPascalTriangle(rowCount);
}