[英]Union and Intersection of Shapes in C++
The following program prints out a diamond and square according to user inputs of rows and length respectively.下面的程序分别根据用户输入的行和长度打印出菱形和正方形。 The shapes are strings with '\\n' for line breaks.形状是带有 '\\n' 换行符的字符串。 I was wondering if theres a way to display the union and intersection of the two shapes, as follows:我想知道是否有一种方法可以显示两个形状的并集和交集,如下所示:
// Example program
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n, i, j, space = 1;
cout<<"enter n for diamond ";
cin>>n;
string dia = "";
space = n - 1;
for (j = 1; j <= n; j++)
{
for (i = 1; i <= space; i++)
{
dia = dia + " ";
}
space--;
for (i = 1; i <= 2 * j - 1; i++)
{
dia=dia+ '*' ;
}
dia = dia+ '\n' ;
}
space = 1;
for (j = 1; j <= n - 1; j++)
{
for (i = 1; i <= space; i++)
{
dia = dia + " ";
}
space++;
for (i = 1; i <= 2 * (n - j) - 1; i++)
{
dia=dia+ '*' ;
}
dia = dia+ '\n' ;
}
cout<<dia;
cout<<"enter s for square ";
int sides;
cin>>sides;
string square = "";
for(int i = 0; i<= sides-1; i++){
if ( i != 0){
square = square + '\n';
}
for (int j = 0; j<=sides-1; j++){
square = square + '*';
}
}
cout<<square;
string intersect = "";
cout<<""<<endl;
}
Output输出
enter n for diamond: 3
*
***
*****
***
*
enter s for square: 4
****
****
****
****
Desired output for union and intersection:并集和交集的期望输出:
Union:
****
****
*****
****
*
Intersection:
*
***
****
***
You should delve a bit deeper into it, with 2d bool arrays:您应该更深入地研究它,使用 2d bool 数组:
int n, s;
cin >> n;
cin >> s;
bool diamond[n*2 - 1][n*2 - 1] {}, square[s][s] {};
void fillDiamond() {
int space = n - 1;
for(int i = 0; i < n*2-1; i++) {
for(int j = 0; j < n*2-1; j++) {
if(j <= space && j > n*2-1 - space) {
diamond[i][j] = true;
}
}
if(i <= n) {
space--;
} else {
space++;
}
}
}
void fillSquare() {
for(int i = 0; i < s; i++) {
for(int j = 0; j < s; j++) {
square[i][j] = true;
}
}
}
fillDiamond();
fillSquare();
bool intersection[max(s, n*2-1)][max(s, n*2-1)] {}, union[max(s, n*2-1)][max(s, n*2-1)] {};
void fillIntersection() {
for(int i = 0; i < max(s, n*2-1); i++) {
for(int j = 0; j < max(s, n*2-1); j++) {
intersection[i][j] = square[i][j] && diamond[i][j]; // check not to go out of bounds!
}
}
}
void fillUnion() {
for(int i = 0; i < max(s, n*2-1); i++) {
for(int j = 0; j < max(s, n*2-1); j++) {
union[i][j] = square[i][j] || diamond[i][j]; // check not to go out of bounds!
}
}
}
fillIntersection();
fillUnion();
// print
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.