Advertisement
Guest User

MatrixSumming2.java SOLUTION

a guest
Jan 22nd, 2020
311
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.16 KB | None | 0 0
  1. //(c) A+ Computer Science
  2. //www.apluscompsci.com
  3. //Name -
  4.  
  5. import java.util.*;
  6. import java.io.*;
  7.  
  8. public class MatrixSumming2
  9. {
  10.     public static int sum( int[][] mat, int r, int c )
  11.     {
  12.         int total = 0;
  13.       total += mat[r][c];
  14.       if( r - 1 >= 0 && c - 1 >= 0 ) total += mat[r-1][c-1];
  15.       if( r - 1 >= 0 ) total += mat[r-1][c];
  16.       if( r - 1 >= 0 && c + 1 < mat[0].length ) total += mat[r-1][c+1];
  17.       if( c - 1 >= 0 ) total += mat[r][c-1];
  18.       if( c + 1 < mat[0].length ) total += mat[r][c+1];
  19.       if( r + 1 < mat.length && c - 1 >= 0 ) total += mat[r+1][c-1];
  20.       if( r + 1 < mat.length ) total += mat[r+1][c];
  21.       if( r + 1 < mat.length && c + 1 < mat.length ) total += mat[r+1][c+1];
  22.       return total;
  23.     }
  24.  
  25.     public static void main(String[] args){
  26.         int[][] m = {{1, 2, 3, 4, 5},
  27.                         {6, 7, 8, 9, 0},
  28.                         {6, 7, 1, 2, 5},
  29.                         {6, 7, 8, 9, 0},
  30.                         {5, 4, 3, 2, 1}};
  31.         System.out.println( sum(m, 2, 2) );
  32.         System.out.println( sum(m, 0, 0) );
  33.         System.out.println( sum(m, 4, 3) );
  34.         System.out.println( sum(m, 4, 4) );
  35.         System.out.println( sum(m, 2, 4) );
  36.         System.out.println( sum(m, 1, 3) );
  37.  
  38.      }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement