Tuesday, November 26, 2024
Google search engine
HomeData Modelling & AIMatrix sum except one item

Matrix sum except one item

Given N*M matrix find the sum of the elements of the matrix without the element specified by its position

Examples: 

Input : mat[] = {{1 2 4}, 
                {5 6 8}}
         cell = (0 2)
Output :22
We need to find sum of all elements
except mat[0][2].

Input : mat[][] = {{5 6 2 3}, {2 3 1 8}, {9 6 5 2}}
        cell = (1 2)
Output :51

Approach 1: A simple solution is to traverse through the matrix. For every visited cell, check if it is the cell to be ignored.

C++




// C++ program to find sum
// of matrix except cell (x, y)
#include<bits/stdc++.h>
using namespace std;
 
// Dimension of input matrix
# define R 2
# define C 3
 
// Returns sum of arr[][]
// except cell arr[x][y]
int calcSum(int arr[R][C],
            int x, int y)
{
    int sum = 0;
    for (int i = 0; i < R; i++)
    {
        for (int j = 0; j < C; j++)
        {
            if (i != x || j != y)
                sum = sum + arr[i][j];
        }
    }
    return sum;
}
 
// Driver code
int main()
{
    int x = 0, y = 2;
    int arr[R][C] = {1, 2, 4,
                     5, 6, 8 };
                     
    cout << calcSum(arr, x, y);
}
 
// This code is contributed
// by ChitraNayal


Java




// Java program to find sum of matrix except
// cell (x, y)
class Matrix {
 
    // Returns sum of arr[][] except cell arr[x][y]
    static int calcSum(int[][] arr, int x, int y)
    {
        int sum = 0;
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr[i].length; j++) {
              if (i != x || j != y)
                sum = sum + arr[i][j];
            }
        }
        return sum;
    }
    public static void main(String[] args)
    {
        int x = 0, y = 2;
        int[][] arr = {
            { 1, 2, 4 }, { 5, 6, 8 },
        };
        System.out.println(calcSum(arr, x, y));
    }
}


C#




// C# program to find sum
// of matrix except cell (x, y)
using System;
 
class GFG
{
 
    // Returns sum of arr[,]
    // except cell arr[x][y]
    static int calcSum(int[,] arr,
                       int x, int y)
    {
        int sum = 0;
        for (int i = 0;
                 i < arr.GetLength(0); i++)
        {
            for (int j = 0;
                     j < arr.GetLength(1); j++)
            {
            if (i != x || j != y)
                sum = sum + arr[i, j];
            }
        }
        return sum;
    }
     
    // Driver Code
    public static void Main()
    {
        int x = 0, y = 2;
        int[,] arr = {{ 1, 2, 4 },
                      { 5, 6, 8 }};
        Console.Write(calcSum(arr, x, y));
    }
}
 
// This code is contributed
// by ChitraNayal


Python 3




# Python 3 program to find
# sum of matrix except cell (x, y)
 
# Returns sum of arr[][]
# except cell arr[x][y]
def calcSum(arr, x, y):
    s = 0
    for i in range(R):
        for j in range(C):
            if (i != x or j != y):
                s = s + arr[i][j];
    return s;
 
# Driver code
x = 0
y = 2
arr = [[ 1, 2, 4 ],
       [ 5, 6, 8 ]]
R = 2
C = 3
 
print(calcSum(arr, x, y))
 
# This code is contributed
# by ChitraNayal


PHP




<?php
// PHP program to find
// sum of matrix except
// cell (x, y)
$R = 2;
$C = 3;
 
// Returns sum of arr[][]
// except cell arr[x][y]
function calcSum(&$arr, $x, $y)
{
    global $R,$C;
    $sum = 0;
    for ($i = 0; $i < $R; $i++)
    {
        for ($j = 0; $j < $C; $j++)
        {
            if ($i != $x || $j != $y)
                $sum = $sum + $arr[$i][$j];
        }
    }
    return $sum;
}
 
// Driver code
$x = 0;
$y = 2;
$arr = array(array(1, 2, 4),
             array(5, 6, 8));
         
echo (calcSum($arr, $x, $y));
 
// This code is contributed
// by ChitraNayal
?>


Javascript




<script>
// Javascript program to find sum of matrix except
// cell (x, y)
     
    // Returns sum of arr[][] except cell arr[x][y]
    function calcSum(arr,x,y)
    {
         let sum = 0;
        for (let i = 0; i < arr.length; i++) {
            for (let j = 0; j < arr[i].length; j++) {
              if (i != x || j != y)
                sum = sum + arr[i][j];
            }
        }
        return sum;
    }
     
    let x = 0, y = 2;
     
    let arr=[[1, 2, 4],[5, 6, 8 ]];
    document.write(calcSum(arr, x, y));
     
// This code is contributed by rag2127
</script>


Output

22

Time Complexity: O(R*C), where R and C are rows and columns of the given matrix|
Auxiliary Space: O(1)

Approach 2: The above solution causes an extra comparison for every matrix item. A better solution is to first find the overall sum, then subtract the given cell.

C++




// C++ program to find sum
// of matrix except cell (x, y)
#include<bits/stdc++.h>
using namespace std;
 
#define R 2
#define C 3
 
// Returns sum of arr[][]
// except cell arr[x][y]
int calcSum(int arr[R][C],
            int x, int y)
{
    int sum = 0;
    for (int i = 0; i < R; i++)
        for (int j = 0; j < C; j++)
            sum = sum + arr[i][j];
 
    return sum - arr[x][y];
}
 
// Driver code
int main()
{
    int x = 0, y = 2;
    int arr[R][C]= {1, 2, 4 ,
                    5, 6, 8 };
 
    cout << (calcSum(arr, x, y));
}
 
// This code is contributed
// by ChitraNayal


Java




// Java program to find sum of matrix except
// cell (x, y)
class Matrix {
 
    // Returns sum of arr[][] except cell arr[x][y]
    static int calcSum(int[][] arr, int x, int y)
    {
        int sum = 0;
        for (int i = 0; i < arr.length; i++)
            for (int j = 0; j < arr[i].length; j++)
                sum = sum + arr[i][j];
 
        return sum - arr[x][y];
    }
 
    public static void main(String[] args)
    {
        int x = 0, y = 2;
        int[][] arr = {
            { 1, 2, 4 }, { 5, 6, 8 },
        };
        System.out.println(calcSum(arr, x, y));
    }
}


C#




// C# program to find sum
// of matrix except cell (x, y)
using System;
 
class GFG
{
 
    // Returns sum of arr[,]
    // except cell arr[x,y]
    static int calcSum(int[,] arr,
                       int x, int y)
    {
        int sum = 0;
        for (int i = 0;
                 i < arr.GetLength(0); i++)
            for (int j = 0;
                     j < arr.GetLength(1); j++)
                sum = sum + arr[i, j];
 
        return sum - arr[x, y];
    }
 
    // Driver code
    public static void Main()
    {
        int x = 0, y = 2;
        int[,] arr = {{ 1, 2, 4 },
                      { 5, 6, 8 }};
        Console.Write(calcSum(arr, x, y));
    }
}
 
// This code is contributed
// by ChitraNayal


Python 3




# Python 3 program to find
# sum of matrix except cell (x, y)
 
# Returns sum of arr[][]
# except cell arr[x][y]
def calcSum( arr, x, y):
    s = 0
    for i in range(R):
        for j in range(C):
            s = s + arr[i][j]
 
    return s - arr[x][y]
 
# Driver code
x = 0
y = 2
R = 2
C = 3
arr = [[1, 2, 4 ],
       [5, 6, 8 ]]
 
print (calcSum(arr, x, y))
 
# This code is contributed
# by ChitraNayal


PHP




<?php
// PHP program to find sum
// of matrix except cell (x, y)
$R = 2;
$C = 3;
 
// Returns sum of $arr[][]
// except cell $arr[$x][$y]
function calcSum(&$arr, $x, $y)
{
    global $R,$C;
    $sum = 0;
    for ($i = 0; $i < $R; $i++)
        for ($j = 0; $j < $C; $j++)
            $sum = $sum + $arr[$i][$j];
 
    return $sum - $arr[$x][$y];
}
 
// Driver code
$x = 0;
$y = 2;
$arr= array(array(1, 2, 4 ),
            array(5, 6, 8 ));
 
echo (calcSum($arr, $x, $y));
 
// This code is contributed
// by ChitraNayal
?>


Javascript




<script>
 
// Javascript program to find sum of matrix except
// cell (x, y)
 
    // Returns sum of arr[][] except cell arr[x][y]
    function calcSum(arr,x,y)
    {
        let sum = 0;
        for (let i = 0; i < arr.length; i++)
            for (let j = 0; j < arr[i].length; j++)
                sum = sum + arr[i][j];
  
        return sum - arr[x][y];
    }
     
    let x = 0, y = 2;
    let arr = [[1, 2, 4 ],
       [5, 6, 8 ]];
 
    document.write(calcSum(arr, x, y));
     
     
 
// This code is contributed by avanitrachhadiya2155
 
</script>


Output

22

Time Complexity: O(R*C) where R and C are rows and columns of a given matrix|
Auxiliary Space: O(1)

Another Approach:

Approach;

Initialize a variable “totalSum” to 0 to keep track of the total sum of all elements in the matrix.

Iterate through each element in the matrix and add its value to “totalSum”.

Iterate through each element in the matrix again, and for each element, subtract its value from “totalSum” if it is not the element to be excluded.

Return the value of “totalSum” as the sum of all elements in the matrix except the excluded element.

C




#include <stdio.h>
 
// Function to find the sum of all elements in the matrix except the excluded element
int matrixSumExceptOne(int matrix[][3], int rows, int cols, int excludedRow, int excludedCol) {
    // Initialize totalSum to 0
    int totalSum = 0;
 
    // Iterate through each element in the matrix and add its value to totalSum
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            totalSum += matrix[i][j];
        }
    }
 
    // Iterate through each element in the matrix again, and for each element,
    // subtract its value from totalSum if it is not the excluded element
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            if (i == excludedRow && j == excludedCol) {
                totalSum -= matrix[i][j];
            }
        }
    }
 
    // Return the value of totalSum as the sum of all elements in the matrix except the excluded element
    return totalSum;
}
 
// Driver code
int main() {
    // Sample input
    int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int excludedRow = 1, excludedCol = 1;
    int rows = 3, cols = 3;
 
    // Find the sum of all elements in the matrix except the excluded element
    int sum = matrixSumExceptOne(matrix, rows, cols, excludedRow, excludedCol);
 
    // Print the result
    printf("The sum of all elements in the matrix except the element at row %d, column %d is %d\n", excludedRow, excludedCol, sum);
 
    return 0;
}


C++




#include <iostream>
using namespace std;
 
// Function to find the sum of all elements in the matrix except the excluded element
int matrixSumExceptOne(int matrix[][3], int rows, int cols, int excludedRow, int excludedCol) {
    // Initialize totalSum to 0
    int totalSum = 0;
 
    // Iterate through each element in the matrix and add its value to totalSum
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            totalSum += matrix[i][j];
        }
    }
 
    // Iterate through each element in the matrix again, and for each element,
    // subtract its value from totalSum if it is not the excluded element
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            if (i == excludedRow && j == excludedCol) {
                totalSum -= matrix[i][j];
            }
        }
    }
 
    // Return the value of totalSum as the sum of all elements in the matrix except the excluded element
    return totalSum;
}
 
// Driver code
int main() {
    // Sample input
    int matrix[3][3] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
    int excludedRow = 1, excludedCol = 1;
    int rows = 3, cols = 3;
 
    // Find the sum of all elements in the matrix except the excluded element
    int sum = matrixSumExceptOne(matrix, rows, cols, excludedRow, excludedCol);
 
    // Print the result
    cout << "The sum of all elements in the matrix except the element at row " << excludedRow
         << ", column " << excludedCol << " is " << sum << endl;
 
    return 0;
}


Java




import java.util.*;
 
public class MatrixSumExceptOne
{
   
    // Function to find the sum of all elements
  // in the matrix except the excluded element
    public static int matrixSumExceptOne(int[][] matrix, int rows,
                                         int cols, int excludedRow,
                                         int excludedCol) {
        // Initialize totalSum to 0
        int totalSum = 0;
 
        // Iterate through each element in
      // the matrix and add its value to totalSum
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                totalSum += matrix[i][j];
            }
        }
 
        // Iterate through each element in the matrix again, and for each element,
        // subtract its value from totalSum if it is not the excluded element
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (i == excludedRow && j == excludedCol) {
                    totalSum -= matrix[i][j];
                }
            }
        }
 
        // Return the value of totalSum as the sum of
      // all elements in the matrix except the excluded element
        return totalSum;
    }
 
    // Driver code
    public static void main(String[] args) {
        // Sample input
        int[][] matrix = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}};
        int excludedRow = 1, excludedCol = 1;
        int rows = 3, cols = 3;
 
        // Find the sum of all elements in the matrix except the excluded element
        int sum = matrixSumExceptOne(matrix, rows, cols, excludedRow, excludedCol);
 
        // Print the result
        System.out.println("The sum of all elements in the matrix except the element at row " + excludedRow +
                           ", column " + excludedCol + " is " + sum);
    }
}
 
// This code is contributed by Sundaram.


Python3




def matrix_sum_except_one(matrix, rows, cols, excluded_row, excluded_col):
    # Initialize total_sum to 0
    total_sum = 0
 
    # Iterate through each element in the matrix and add its value to total_sum
    for i in range(rows):
        for j in range(cols):
            total_sum += matrix[i][j]
 
    # Iterate through each element in the matrix again, and for each element,
    # subtract its value from total_sum if it is not the excluded element
    for i in range(rows):
        for j in range(cols):
            if i == excluded_row and j == excluded_col:
                total_sum -= matrix[i][j]
 
    # Return the value of total_sum as the sum of all elements in the matrix except the excluded element
    return total_sum
 
 
# Sample input
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
excluded_row = 1
excluded_col = 1
rows = 3
cols = 3
 
# Find the sum of all elements in the matrix except the excluded element
sum = matrix_sum_except_one(matrix, rows, cols, excluded_row, excluded_col)
 
# Print the result
print("The sum of all elements in the matrix except the element at row", excluded_row,
      "column", excluded_col, "is", sum)


C#




using System;
 
class MatrixSumExceptOneClass
{
    // Function to find the sum of all elements
    // in the matrix except the excluded element
    public static int MatrixSumExceptOne(int[,] matrix, int rows,
                                         int cols, int excludedRow,
                                         int excludedCol)
    {
        // Initialize totalSum to 0
        int totalSum = 0;
 
        // Iterate through each element in
        // the matrix and add its value to totalSum
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                totalSum += matrix[i, j];
            }
        }
 
        // Iterate through each element in the matrix again, and for each element,
        // subtract its value from totalSum if it is not the excluded element
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < cols; j++)
            {
                if (i == excludedRow && j == excludedCol)
                {
                    totalSum -= matrix[i, j];
                }
            }
        }
 
        // Return the value of totalSum as the sum of
        // all elements in the matrix except the excluded element
        return totalSum;
    }
 
    // Driver code
    static void Main(string[] args)
    {
        // Sample input
        int[,] matrix = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
        int excludedRow = 1, excludedCol = 1;
        int rows = 3, cols = 3;
 
        // Find the sum of all elements in the matrix except the excluded element
        int sum = MatrixSumExceptOne(matrix, rows, cols, excludedRow, excludedCol);
 
        // Print the result
        Console.WriteLine("The sum of all elements in the matrix except the element at row " + excludedRow +
                           ", column " + excludedCol + " is " + sum);
    }
}


Javascript




// Function to find the sum of all elements in the matrix except the excluded element
function matrixSumExceptOne(matrix, rows, cols, excludedRow, excludedCol) {
  // Initialize totalSum to 0
  let totalSum = 0;
 
  // Iterate through each element in the matrix and add its value to totalSum
  for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
      totalSum += matrix[i][j];
    }
  }
 
  // Iterate through each element in the matrix again, and for each element,
  // subtract its value from totalSum if it is not the excluded element
  for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
      if (i === excludedRow && j === excludedCol) {
        totalSum -= matrix[i][j];
      }
    }
  }
 
  // Return the value of totalSum as the sum of all elements in the matrix except the excluded element
  return totalSum;
}
 
// Driver code
// Sample input
const matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
const excludedRow = 1, excludedCol = 1;
const rows = 3, cols = 3;
 
// Find the sum of all elements in the matrix except the excluded element
const sum = matrixSumExceptOne(matrix, rows, cols, excludedRow, excludedCol);
 
// Print the result
console.log(`The sum of all elements in the matrix except the element at row ${excludedRow}, column ${excludedCol} is ${sum}`);


Output

The sum of all elements in the matrix except the element at row 1, column 1 is 40

 time complexity of O(N*M), Where N is the number of rows and M is the number of columns in the matrix

 space complexity of O(1)

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments