c++ - C++中形状的并集和交集
问题描述
以下程序分别根据用户输入的行和长度打印出菱形和正方形。形状是带有 '\n' 的字符串,用于换行。我想知道是否有一种方法可以显示两个形状的并集和交集,如下所示:
// 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;
}
输出
enter n for diamond: 3
*
***
*****
***
*
enter s for square: 4
****
****
****
****
联合和交集的期望输出:
Union:
****
****
*****
****
*
Intersection:
*
***
****
***
解决方案
您应该使用 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
推荐阅读
- caffe - caffe softmax with loss layer 用于语义分割损失计算
- css - 元素仅在检查元素/调整浏览器窗口后出现
- python - Jinja2 不适用于 flask/glitch.me 部署
- cloud-foundry - PCF Staticfile_buildpack 不考虑静态文件
- javascript - 为什么 React 将我的数组视为空的?
- jquery - 将焦点添加到单击的按钮
- postgresql - PostgreSQL 序列连接到列
- python - 使用 LIKE 和 % 通配符在通过 python 执行的 mySQL 查询中转义“%”
- angular - 使用 Angular 5 轮询端点并合并接收到的数据
- android - Android Glide:使用签名进行缓存的正确方法