Reputation: 37
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. 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:
*
***
****
***
Upvotes: 1
Views: 199
Reputation: 197
You should delve a bit deeper into it, with 2d bool arrays:
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
Upvotes: 1