简体   繁体   中英

How to convert this extensive Python loop to C++?

I know very little on Python, but I'm quite experienced in C++. I was looking for an algorithm that would loop through the points in a hexagon pattern and found one written in Python that seems to be exactly what I need. The problem is that I have no idea how to interpret it.

Here is the Python code:

for x in [(n-abs(x-int(n/2))) for x in range(n)]:
    for y in range(n-x):
        print ' ',
    for y in range(x):
        print ' * ',
    print

I'd show you my attempts but there are like 30 different ones that all failed (which I'm sure are just my bad interpretation).

Hope this helps you.Tested both python and c++ code .Got same results.

#include <iostream>
#include <cmath> 

using namespace std;

int main() {
    // your code goes here
    int n = 10;
    int a[n];

    for(int j = 0; j < n; j++) {
       a[j] = n - abs(j - (n / 2)); 
    }

    for(int x = 0; x < n; x++) {
        for(int y = 0; y < (n - a[x]); y++) {
            std::cout << " " << std::endl;
        }
    }

    for(int k = 0; k < a[n-1]; k++) {
        std::cout << " * " << std::endl;
    }

    std::cout << "i" << std::endl;

    return 0;
}
auto out = ostream_iterator<const char*>(cout," ");

for(int i = 0; i != n; ++i) {
    auto width = n - abs(i - n/2);
    fill_n(out, n-width, " ");
    fill_n(out, width, " * ");
    cout << "\n";
}

Live demo .

Python live demo for reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM