How to build a pyramid from the numbers 3, 7, 5, 2, 4, 8, 6, 9, 0, 3 in C++

1 Answer

0 votes
#include <iostream>
#include <vector>

using std::vector;

// ------------------------------------------------------------
// Build a pyramid from a flat list of numbers
// ------------------------------------------------------------
vector<vector<int>> buildPyramid(const vector<int>& nums) {
    vector<vector<int>> pyramid;
    int index = 0;
    int rowSize = 1;

    while (index + rowSize <= nums.size()) {
        vector<int> row;
        for (int i = 0; i < rowSize; i++) {
            row.push_back(nums[index++]);
        }
        pyramid.push_back(row);
        rowSize++;
    }

    return pyramid;
}

// ------------------------------------------------------------
// Print the pyramid centered
// ------------------------------------------------------------
void printPyramid(const vector<vector<int>>& pyramid) {
    int height = pyramid.size();

    for (int r = 0; r < height; r++) {
        // Print leading spaces
        std::cout << std::string((height - r - 1) * 2, ' ');

        // Print row values
        for (int v : pyramid[r]) {
            std::cout << v << "   ";
        }
        std::cout << "\n";
    }
}

// ------------------------------------------------------------
// Main program
// ------------------------------------------------------------
int main() {
    vector<int> numbers = {3, 7, 5, 2, 4, 8, 6, 9, 0, 3};

    auto pyramid = buildPyramid(numbers);

    std::cout << "Pyramid:\n";
    printPyramid(pyramid);
}


/*
run:

Pyramid:
      3   
    7   5   
  2   4   8   
6   9   0   3   

*/

 



answered 3 hours ago by avibootz
...