Given a sorted matrix of size n*n. Calculate the mean and median of the matrix .
Examples:
Input : 1 2 3
4 5 6
7 8 9
Output :Mean: 5
Median: 5
Input : 1 1 1
2 2 2
4 4 4
Output :Mean: 2
Median: 2
Mean of matrix is =
(sum of all elements of matrix)/
(total elements of matrix)
Note that this definition doesn't require
matrix to be sorted and works for all
matrices.
Median of a sorted matrix is calculated as:
1. When n is odd
median is mat[n/2][n/2]
2. When n is even, median is average
of middle two elements.
Middle two elements can be found at indexes
a[(n-2)/2][n-1] and a[n/2][0]
If given matrix is unsorted, we can find its median by first sorting the matrix.
Implementation:
// CPP program to find mean and median // of sorted square matrix. #include <bits/stdc++.h> using namespace std;
const int N = 4;
// Returns mean of a given matrix of // size n x n. double findMean( int a[][N])
{ int sum = 0;
// total sum calculation of matrix
for ( int i=0; i<N; i++)
for ( int j=0; j<N; j++)
sum += a[i][j];
return ( double )sum/(N*N);
} // Function for calculating median double findMedian( int a[][N])
{ if (N % 2 != 0)
return a[N/2][N/2];
if (N%2 == 0)
return (a[(N-2)/2][N-1] +
a[N/2][0])/2.0;
} // Driver program int main()
{ int a[N][N]= {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}};
cout << "Mean : " << findMean(a) << endl
<< "Median : " << findMedian(a) << endl;
return 0;
} |
// C program to find mean and median // of sorted square matrix. #include <stdio.h> #define N 4 // Returns mean of a given matrix of // size n x n. double findMean( int a[][N])
{ int sum = 0;
// total sum calculation of matrix
for ( int i=0; i<N; i++)
for ( int j=0; j<N; j++)
sum += a[i][j];
return ( double )sum/(N*N);
} // Function for calculating median double findMedian( int a[][N])
{ if (N % 2 != 0)
return a[N/2][N/2];
if (N%2 == 0)
return (a[(N-2)/2][N-1] +
a[N/2][0])/2.0;
} // Driver program int main()
{ int a[N][N]= {{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}};
printf ( "Mean : %f\n" ,findMean(a));
printf ( "Median : %f\n" ,findMedian(a));
return 0;
} // This code is contributed by kothavvsaakash. |
// Java program to find mean and median // of sorted square matrix. import java.io.*;
class GFG
{ // Returns mean of a given // matrix of size n x n. static double findMean( int a[][],
int n)
{ int sum = 0 ;
int N=n;
// total sum calculation of matrix
for ( int i = 0 ; i < N; i++)
for ( int j = 0 ; j < N; j++)
sum += a[i][j];
return ( double )sum / (N * N);
} // Function for calculating median static double findMedian( int a[][], int n)
{ int N = n;
if (N % 2 != 0 )
return a[N / 2 ][N / 2 ];
if (N % 2 == 0 )
return (a[(N - 2 ) / 2 ][ N - 1 ] +
a[ N / 2 ][ 0 ]) / ( 2.0 );
return 0 ;
} // Driver Code
public static void main (String[] args)
{
int a[][]= {{ 1 , 2 , 3 , 4 },
{ 5 , 6 , 7 , 8 },
{ 9 , 10 , 11 , 12 },
{ 13 , 14 , 15 , 16 }};
int n = a.length;
System.out.println( "Mean : " +
findMean(a, n));
System.out.println( "Median : " +
findMedian(a, n));
}
} // This code is contributed by KRV. |
# Python3 program to find mean and median # of sorted square matrix. N = 4
# Returns mean of a given matrix of # size n x n. def findMean(a):
summ = 0
# total sum calculation of matrix
for i in range (N):
for j in range (N):
summ + = a[i][j]
return summ / (N * N)
# Function for calculating median def findMedian(a):
if (N % 2 ! = 0 ):
return a[N / / 2 ][N / / 2 ]
if (N % 2 = = 0 ):
return (a[(N - 2 ) / / 2 ][N - 1 ] + a[N / / 2 ][ 0 ]) / 2
# Driver program a = [[ 1 , 2 , 3 , 4 ],[ 5 , 6 , 7 , 8 ],
[ 9 , 10 , 11 , 12 ],[ 13 , 14 , 15 , 16 ]]
print ( "Mean :" , findMean(a))
print ( "Median :" ,findMedian(a))
# This code is contributed by shubhamsingh10 |
// C# program to find mean and median // of sorted square matrix. using System;
class GFG {
// Returns mean of a given
// matrix of size n x n.
static double findMean( int [,]a, int n)
{
int sum = 0;
int N = n;
// total sum calculation of matrix
for ( int i = 0; i < N; i++)
for ( int j = 0; j < N; j++)
sum += a[i,j];
return ( double )sum / (N * N);
}
// Function for calculating median
static double findMedian( int [,]a, int n)
{
int N = n;
if (N % 2 != 0)
return a[N / 2,N / 2];
if (N % 2 == 0)
return ( a[(N - 2) / 2, (N - 1)] +
a[ N / 2, 0] ) / (2.0);
return 0;
}
// Driver Code
public static void Main ()
{
int [,]a= { { 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9, 10, 11, 12},
{13, 14, 15, 16} };
int n = a.GetLength(0);
Console.WriteLine( "Mean : " +
findMean(a, n));
Console.WriteLine( "Median : " +
findMedian(a, n));
}
} // This code is contributed by Sam007. |
<script> // Javascriptprogram to find mean and median // of sorted square matrix. // Returns mean of a given // matrix of size n x n. function findMean(a, n)
{ var sum = 0;
var N = n;
// Total sum calculation of matrix
for ( var i = 0; i < N; i++)
for ( var j = 0; j < N; j++)
sum += a[i][j];
return sum / (N * N);
} // Function for calculating median function findMedian(a, n)
{ var N = n;
if (N % 2 != 0)
return a[N / 2][N / 2];
if (N % 2 == 0)
return (a[(N - 2) / 2][ N - 1] +
a[N / 2][0]) / (2.0);
return 0;
} // Driver Code var a = [ [ 1, 2, 3, 4 ],
[ 5, 6, 7, 8 ],
[ 9, 10, 11, 12 ],
[ 13, 14, 15, 16 ] ];
var n = a.length;
document.write( "Mean : " +
findMean(a, n) + "<br>" );
document.write( "Median : " +
findMedian(a, n) + "<br>" );
// This code is contributed by Kirti </script> |
<?php // PHP program to find // mean and median // of sorted square // matrix. $N = 4;
// Returns mean of // a given matrix of // size n x n. function findMean( $a )
{ global $N ;
$sum = 0;
// total sum calculation
// of matrix
for ( $i = 0; $i < $N ; $i ++)
for ( $j = 0; $j < $N ; $j ++)
$sum += $a [ $i ][ $j ];
return (double) $sum / ( $N * $N );
} // Function for calculating median function findMedian( $a )
{ global $N ;
if ( $N % 2 != 0)
return $a [ $N / 2][ $N / 2];
if ( $N % 2 == 0)
return ( $a [( $N - 2) / 2][ $N - 1] +
$a [ $N / 2][0]) / 2.0;
} // Driver Code
$a = array ( array (1, 2, 3, 4),
array (5, 6, 7, 8),
array (9, 10, 11, 12),
array (13, 14, 15, 16));
echo "Mean : " , findMean( $a ), "\n" ,
"Median : " , findMedian( $a );
// This code is contributed by vt_m. ?> |
Mean : 8.5 Median : 8.5
Time complexity: O(N2) as using two for loops
Auxiliary Space: O(1)
METHOD 2:Using functions
APPROACH:
This Python program calculates the mean and median of a given matrix using functions. The program first defines two functions – mean() and median(), which take the matrix as an argument and return the calculated mean and median values, respectively. It then creates a 3×3 matrix and calls these functions to calculate the mean and median of the matrix. Finally, the program prints out the calculated mean and median values.
ALGORITHM:
-
Define the mean() function that takes the matrix as an argument.
- Calculate the total sum of all the values in the matrix.
- Calculate the number of values in the matrix.
- Divide the total sum by the number of values to get the mean.
- Return the mean value.
- Define the median() function that takes the matrix as an argument.
- Flatten the matrix into a 1D list.
- Sort the list in ascending order.
- Calculate the length of the list.
- If the length of the list is even, calculate the average of the middle two values.
- If the length of the list is odd, return the middle value.
- Return the median value.
// C++ Program for the above approach #include <bits/stdc++.h> using namespace std;
// function to find out mean value double mean(vector<vector< int >>& matrix) {
int total = 0;
int count = matrix.size() * matrix[0].size();
for ( const auto & row : matrix) {
for ( int val : row) {
total += val;
}
}
return static_cast < double >(total) / count;
} // Function to find out the media value double median(vector<vector< int >>& matrix) {
vector< int > flatten;
for ( const auto & row : matrix) {
for ( int val : row) {
flatten.push_back(val);
}
}
// sorting the flatten array
sort(flatten.begin(), flatten.end());
int n = flatten.size();
if (n % 2 == 0) {
return ( static_cast < double >(flatten[n/2]) + flatten[n/2-1]) / 2;
} else {
return flatten[n/2];
}
} // Driver Program to test above functions int main() {
// Given Matrix
vector<vector< int >> matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
double mean_value = mean(matrix);
double median_value = median(matrix);
cout << "Mean: " << mean_value << endl;
cout << "Median: " << median_value << endl;
return 0;
} // THIS CODE IS CONTRIBUTED BY KIRTI AGARWAL |
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Main {
// function to find out mean value
static double mean(List<List<Integer> > matrix)
{
int total = 0 ;
int count = matrix.size() * matrix.get( 0 ).size();
for (List<Integer> row : matrix) {
for ( int val : row) {
total += val;
}
}
return ( double )total / count;
}
// Function to find out the median value
static double median(List<List<Integer> > matrix)
{
List<Integer> flatten = new ArrayList<>();
for (List<Integer> row : matrix) {
for ( int val : row) {
flatten.add(val);
}
}
// sorting the flatten array
Collections.sort(flatten);
int n = flatten.size();
if (n % 2 == 0 ) {
return (( double )flatten.get(n / 2 )
+ flatten.get(n / 2 - 1 ))
/ 2 ;
}
else {
return flatten.get(n / 2 );
}
}
// Driver Program to test above functions
public static void main(String[] args)
{
// Given Matrix
List<List<Integer> > matrix = new ArrayList<>();
matrix.add( new ArrayList<>(List.of( 1 , 2 , 3 )));
matrix.add( new ArrayList<>(List.of( 4 , 5 , 6 )));
matrix.add( new ArrayList<>(List.of( 7 , 8 , 9 )));
double mean_value = mean(matrix);
double median_value = median(matrix);
System.out.println( "Mean: " + mean_value);
System.out.println( "Median: " + median_value);
}
} // This code is contributed by akshitaguprzj3 |
def mean(matrix):
total = sum (val for row in matrix for val in row)
count = len (matrix) * len (matrix[ 0 ])
return total / count
def median(matrix):
flatten = [val for row in matrix for val in row]
flatten.sort()
n = len (flatten)
if n % 2 = = 0 :
return (flatten[n / / 2 ] + flatten[n / / 2 - 1 ]) / 2
else :
return flatten[n / / 2 ]
# Create a 3x3 matrix matrix = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ]]
# Calculate mean and median mean_value = mean(matrix)
median_value = median(matrix)
# Print the results print ( "Mean:" , mean_value)
print ( "Median:" , median_value)
|
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{ // Function to find out mean value
static double Mean(List<List< int >> matrix)
{
int total = 0;
int count = matrix.Count * matrix[0].Count;
foreach ( var row in matrix)
{
foreach ( int val in row)
{
total += val;
}
}
return ( double )total / count;
}
// Function to find out the median value
static double Median(List<List< int >> matrix)
{
List< int > flatten = new List< int >();
foreach ( var row in matrix)
{
foreach ( int val in row)
{
flatten.Add(val);
}
}
// Sorting the flatten list
flatten.Sort();
int n = flatten.Count;
if (n % 2 == 0)
{
return (( double )flatten[n / 2] + flatten[n / 2 - 1]) / 2;
}
else
{
return flatten[n / 2];
}
}
// Driver Program to test above functions
static void Main( string [] args)
{
// Given Matrix
List<List< int >> matrix = new List<List< int >>
{
new List< int > {1, 2, 3},
new List< int > {4, 5, 6},
new List< int > {7, 8, 9}
};
double meanValue = Mean(matrix);
double medianValue = Median(matrix);
Console.WriteLine($ "Mean: {meanValue}" );
Console.WriteLine($ "Median: {medianValue}" );
}
} // This code is contributed by akshitaguprzj3 |
// Function to calculate the mean of a matrix function mean(matrix) {
let total = matrix.flat().reduce((sum, val) => sum + val, 0);
let count = matrix.length * matrix[0].length;
return total / count;
} // Function to calculate the median of a matrix function median(matrix) {
let flatten = matrix.flat().sort((a, b) => a - b);
let n = flatten.length;
if (n % 2 === 0) {
return (flatten[n / 2] + flatten[n / 2 - 1]) / 2;
} else {
return flatten[Math.floor(n / 2)];
}
} // Create a 3x3 matrix let matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; // Calculate mean and median let meanValue = mean(matrix); let medianValue = median(matrix); // Print the results console.log( "Mean:" , meanValue);
console.log( "Median:" , medianValue);
// THIS CODE IS CONTRIBUTED BY KIRTI AGARWAL |
Mean: 5.0 Median: 5
Time Complexity: The time complexity of this program is O(nlogn) for sorting the list, where n is the total number of elements in the matrix.
Space Complexity: The space complexity of this program is O(n) for storing the flattened list, where n is the total number of elements in the matrix.