C++ Program to find table plate ordering maintaining given conditions

C++Server Side ProgrammingProgramming

Suppose we have two numbers h and w. The height and width of a table. The table is divided into h × w cells. Into each cell of the table, we can either put a plate or keep it empty. As each guest has to be seated next to their plate, we can only put plates on the edge of the table — into the first or the last row of the rectangle, or into the first or the last column. To make the guests comfortable, no two plates must be put into cells that have a common side or corner. In other words, if the cell (i,j) contains a plate, we can't put plates into cells (i−1,j), (i,j−1), (i+1,j), (i,j+1), (i−1,j−1), (i−1,j+1), (i+1,j−1), (i+1,j+1). Put as many plates as possible with maintaining the above rules. We have to print the table current status.

Problem Category

An array in the data structure is a finite collection of elements of a specific type. Arrays are used to store elements of the same type in consecutive memory locations. An array is assigned a particular name and it is referenced through that name in various programming languages. To access the elements of an array, indexing is required. We use the terminology 'name[i]' to access a particular element residing in position 'i' in the array 'name'. Various data structures such as stacks, queues, heaps, priority queues can be implemented using arrays. Operations on arrays include insertion, deletion, updating, traversal, searching, and sorting operations. Visit the link below for further reading.

https://www.tutorialspoint.com/data_structures_algorithms/array_data_structure.htm

So, if the input of our problem is like h = 3; w = 5, then the output will be

10101
00000
10101

Steps

To solve this, we will follow these steps −

for initialize i := 1, when i <= h, update (increase i by 1), do:
   for initialize j := 1, when j <= w, update (increase j by 1), do:
      if i is same as 1 or i is same as h, then:
         print 1 if (j AND 1) is 1, otherwise 0
      otherwise when i is not equal to 2 and i is not equal to h - 1 and i is odd and (j is same as 1 or j is same as w), then:
         print 1
      Otherwise
         print 0
   move cursor to the next line

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
void solve(int h, int w){
   for (int i = 1; i <= h; ++i){
      for (int j = 1; j <= w; ++j){
         if (i == 1 || i == h)
            cout << ((j & 1)) << " ";
         else if (i != 2 && i != h - 1 && (i & 1) && (j == 1 || j == w))
            cout << 1 << " ";
         else
            cout << 0 << " ";
      }
      cout << endl;
   }
}
int main(){
   int h = 3;
   int w = 5;
   solve(h, w);
}

Input

3, 5

Output

1 0 1 0 1
0 0 0 0 0
1 0 1 0 1
raja
Updated on 08-Apr-2022 11:12:45

Advertisements