In hình ngôi nhà (hut) với chiều rộng N (số lẻ). Hình bao gồm mái nhà (tam giác), thân nhà (hình chữ nhật) và cửa (dùng ký tự '_' và '|').
Ví dụ minh họa (C++)
#include <iostream>
using namespace std;
int print_hut(int n) {
if (n % 2 == 0) n++; // đảm bảo lẻ
for (int i = 0; i <= n - n / 3; i++) {
for (int j = 0; j < n; j++) {
int t = 2 * n / 5;
if (t % 2 != 0) t--;
// Vẽ viền mái và thân
if (i == n / 5 || i == n - n / 3 ||
(j == n - 1 && i >= n / 5) ||
(j >= n / 5 && j < n - n / 5 && i == 0) ||
(j == 0 && i >= n / 5) ||
(j == t && i > n / 5) ||
(i <= n / 5 && (i + j == n / 5 || j - i == n / 5)) ||
(j - i == n - n / 5)) {
cout << "*";
}
// Vẽ cửa
else if (i == n / 5 + n / 7 && (j >= n / 7 && j <= t - n / 7)) {
cout << "_";
}
else if (i >= n / 5 + n / 7 && (j == n / 7 || j == t - n / 7)) {
cout << "|";
}
else cout << " ";
}
cout << "\n";
}
}
int main() {
int n = 12;
print_hut(n);
return 0;
}
Kết quả
********** * * * * ************* *____* *| |* *| |* *| |* *| |* *| |* *************