Number of elements greater than modified mean in matrix in C++

C++Server Side ProgrammingProgramming

<p>The modified mean of the matrix is defined as follows...</p><p>(sum(row-wise min) + sum(column-wise max)) / (row_size + column_size)</p><p>Let&#39;s see an example.</p><pre class="result notranslate">1 2 3 4 5 6 7 8 9</pre><p>mean = (sum(1 + 4 + 7) + sum(7 + 8 + 9)) / (3 + 3)</p><p>We have to find the mean first and then count the number of elements that are greater than mean.</p><p>If we take the above example, then we will get 3 as the count. There are 3 elements that are greater than the mean which is 6.</p><h2>Algorithm</h2><ul class="list"><li><p>Initialise the matrix.</p></li><li><p>Find the row-wise minimum elements sum.</p></li><li><p>Find the column-wise maximum elements sum.</p></li><li><p>Then find the mean with above mentioned formula.</p></li><li><p>Now, count the number of elements greater than the mean of the matrix.</p></li></ul><h2>Implementation</h2><p>Following is the implementation of the above algorithm in C++</p><pre class="demo-code notranslate language-cpp" data-lang="cpp">#include &lt;bits/stdc++.h&gt; using namespace std; #define m 3 #define n 3 int getElementCountGreaterThanMean(int matrix[][n]) { &nbsp; &nbsp;int rowSum = 0; &nbsp; &nbsp;for (int i = 0; i &lt; m; i++) { &nbsp; &nbsp; &nbsp; int min = matrix[i][0]; &nbsp; &nbsp; &nbsp; for (int j = 1; j &lt; n; j++) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (matrix[i][j] &lt; min){ &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; min = matrix[i][j]; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; rowSum += min; &nbsp; &nbsp;} &nbsp; &nbsp;int colSum = 0; &nbsp; &nbsp;for (int i = 0; i &lt; n; i++) { &nbsp; &nbsp; &nbsp; int max = matrix[0][i]; &nbsp; &nbsp; &nbsp; for (int j = 1; j &lt; m; j++) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (max &lt; matrix[j][i]) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; max = matrix[j][i]; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp; &nbsp; colSum += max; &nbsp; &nbsp;} &nbsp; &nbsp;int mean = (rowSum + colSum) / (m + n); &nbsp; &nbsp;int count = 0; &nbsp; &nbsp;for (int i = 0; i &lt; m; i++) { &nbsp; &nbsp; &nbsp; for (int j = 0; j &lt; n; j++) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;if (mean &lt; matrix[i][j]) { &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; count++; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;} &nbsp; &nbsp; &nbsp; } &nbsp; &nbsp;} &nbsp; &nbsp;return count; } int main() { &nbsp; &nbsp;int matrix[m][n] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; &nbsp; &nbsp;cout &lt;&lt; getElementCountGreaterThanMean(matrix) &lt;&lt; endl; &nbsp; &nbsp;return 0; }</pre><h2>Output</h2><p>If you run the above code, then you will get the following result.</p><pre class="result notranslate">3</pre>
Updated on 26-Oct-2021 07:20:06