Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write C++ code to build two grids which are each X wide and Y long where X and Y

ID: 2247894 • Letter: W

Question

Write C++ code to build two grids which are each X wide and Y long where X and Y are user inputs to determine the size of the grids. Fill each cell of both grids with a ‘0’. Randomly fill 1/3rd of the grid’s cells with a ‘1’. You must randomly fill each of the two grids separately so they do not have all the same squares filled with ‘1’. Compare the two grids (square by square comparison) to find squares which have a ‘1’ in both grids. Create a third grid which contains a ‘1’ in squares where both of the compared grids contain a ‘1’ and has a ‘0’ in any other square.

Example in a 2 by 2 grid:

Grid1

0 0

1 1

Grid2

1 0

1 0

Grid3(Result)

0 0

1 0


For this assignment, you will need to create a Grid Class and the appropriate methods to perform the above operations.

Is there some to help me to write C++ code for this assignment?

Explanation / Answer

#include<iostream>
#include <stdlib.h>    
#include <time.h>      

using namespace std;

class Grid {
   private:
      int x,y;
      int **data;
   public:
      Grid(int a, int b){
         x = a;
         y = b;
         data = new int*[a];
         for (int i = 0; i<a; i++){
             data[i] = new int[b];
         }       
      }
      void Fill(){
        
         int num = (x*y)/3;
          for (int i = 0; i<=num; i++){
               data[rand()%x][rand()%y] = 1;      
          }
      }
      int **getData(){
            return data;
      }
      void disp(){
         for (int i=0; i<x; i++){
            for(int j = 0; j<y; j++){
                cout << data[i][j] << " ";
            }
            cout << endl;
         }
      }
};


int main(){
int a,b;
cout << "Enter dimensions for grid (x and y): " << endl;
cin >> a >> b;
srand (time(NULL));
Grid g1(a,b);
Grid g2(a,b);
Grid g3(a,b);
g1.Fill();
g2.Fill();
for (int i = 0; i<a; i++){
      for (int j = 0; j<b; j++){
          if (g1.getData()[i][j] == 1 && g2.getData()[i][j] == 1)
              g3.getData()[i][j] = 1;
          else
              g3.getData()[i][j] = 0;       
      }
}
cout << "The first grid:" << endl;
g1.disp();
cout << "The second grid:" << endl;
g2.disp();
cout << "The third grid:" << endl;
g3.disp();

return 0;
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote