C++ code to find score of winning square on a square board

C++Server Side ProgrammingProgramming

Suppose we have a square board of order n x n. Amal and Bimal are playing a game. During the game they write numbers on the board's squares by some unknown rules. Currently the board is showing elements after ending the game. To understand who has won, we need to count the number of winning squares. A particular square is winning we should do the following. Find the sum of all numbers on the squares that share this column and separately calculate the sum of all numbers on the squares that share this row. A square is a winning square if the sum of the column numbers is strictly greater than the sum of the row numbers.

So, if the input is like

5784
9532
1664
9573

Then the output will be 6, because

5784
9532
1664
9573

Steps

To solve this, we will follow these steps −

t := 0
n := size of M
for initialize i := 0, when i <= n - 1, update (increase i by 1), do:
   for initialize j := 0, when j <= n - 1, update (increase j by 1), do:
      s := 0
   l := 0
   for initialize k := 0, when k <= n - 1, update (increase k by 1), do:
      s := s + M[i, k]
      l := l + M[k, j]
   if l > s, then:
      (increase t by 1)
return t

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
int solve(vector<vector<int>> M){
   int t = 0;
   int n = M.size();
   for (int i = 0; i <= n - 1; i++)
   for (int j = 0; j <= n - 1; j++){
      int s = 0;
      int l = 0;
      for (int k = 0; k <= n - 1; k++){
         s += M[i][k];
         l += M[k][j];
      }
      if (l > s)
         t++;
   }
   return t;
}
int main(){
   vector<vector<int>> matrix = { { 5, 7, 8, 4 }, { 9, 5, 3, 2 }, { 1, 6, 6, 4 }, { 9, 5, 7, 3 } };
   cout << solve(matrix) << endl;
}

Input

{ { 5, 7, 8, 4 }, { 9, 5, 3, 2 }, { 1, 6, 6, 4 }, { 9, 5, 7, 3 } }

Output

6
raja
Updated on 30-Mar-2022 14:29:07

Advertisements