finding sum of two dimensional array java

56,944

Solution 1

I reccomend you do it this way:

int perTotal = 0;
// top and bottom row
for (int c = 0; c < numCols; c++)
    perTotal += matrix[0][c] + matrix[numRows-1][c];
// left and right column
for (int r = 1; r < numRows-1; r++)
    perTotal += matrix[r][0] + matrix[r][numCols-1];

// output
System.out.println("Perimeter=" + perTotal);

Solution 2

Here is your method:

public static int perimeter(int[][] array) {
    int perimter = 0;
    for (int i = 0; i < array[0].length; i++) {
        perimter += array[0][i] + array[array.length - 1][i];
    }
    for (int r = 1; r < array.length - 1; r++) {
        perimter += array[r][0] + array[r][array[0].length - 1];
    }
    return perimter;
}

And here is your test with the array you provided :

public static void main(String[] args) { System.out.println(perimeter(new int[][]{{1, 2, 2, 3}, {2, 4, 4, 2}, {3, 6, 6, 3}, {4, 8, 8, 4}})); }

Output : 42

Solution 3

There is a la4j (Linear Algebra for Java) library that handles this task in 0.4.0 release (currently avaliable at GitHub: https://github.com/vkostyukov/la4j, will be avaliable at Maven this summer). So, here is the brief example:

Matrix a = new Basic2DMatrix(...); // creates a real matrix

// calculates the sum of '1' row
double d1 = a.foldRow(1, Matrices.asSumAccumulator(0)); 
// calculates the sum of '2' 
double d2 = a.foldColumn(2, Matrices.asSumAccumulator(0));

// the helper class that fetches border elements of matrix
class PerimeterFetcher implements MatrixFunction {

  private int rows;
  private int columns;

  public PerimeterFectcher(int rows, int columns) {
    this.rows = rows;
    this.columns = columns;
  }      

  @Override
  public double evaluate(int i, int j, double value) {
    return i == 0 ? value : j == 0 ? value : (i + 1) == rows ? value
           : (j + 1) == columns ? value : 0;
  }
}

// calculates the perimeter of matrix
double p = a.fold(Matrices.asSumFunctionAccumulator(0, 
                  new PerimeterFetcher(a.rows(), a.columns())));     

UPD: The next version of la4j (0.4.5) supports sum() method for matrices and vectors:

Matrix a = new Basic2DMatrix(...);
double s = a.sum(); // wrapper around a.fold(...);

Solution 4

Just do this:

        for (int i = 0; i < ROWS; i++){
           for (int j = 0; j < COLUMNS; j++){
             sum = sum + myArray[i][j];
        }
    }

    System.out.print(sum);

This should give you the sum.

Solution 5

        //Requirement #7: traverse the perimeter and sum the values and display the sum

        int perTotal = 0;

        // First line
        for (int j = 0; j < numCols; j++)
        {
            perTotal += matrix[0][j];
        }

        // If there is only one line, then it is done.
        if (numRows > 1)
        {
            // Last line
            for (int j = 0; j < numCols; j++)
            {
                perTotal += matrix[numRows-1][j];
            }

            // Other lines
            for (int i = 1; i < numRows -1); i++)
            {
                perTotal += matrix[i][0] + matrix[i][numcols -1];
            }
        }

    //Perimeter
    System.out.println("Perimter="+perTotal);
Share:
56,944
maggie
Author by

maggie

Updated on April 15, 2021

Comments

  • maggie
    maggie about 3 years

    I am working on a project where I have to read a file and enter the content into a 2D array. Then I have to sum each row, each column, and the perimeter of the matrix. I have everything working so far except the perimeter. I am trying to create separate for loops for the top row, bottom row, and middle of the two outside columns.

    The matrix file looks like this:

    1 2 3 4 
    2 4 6 8 
    2 4 6 8 
    3 2 3 4 
    

    Therefore the perimeter should add up to 42. Right now I can successfully add the first row and the last row to equal 22. However, when I add the columns to that total I get 32.

    Here is the code:

    import java.util.*; // Scanner class
    import java.io.*;  // File class
    
    public class Lab10
    {
       static public void main( String [ ] args )  throws Exception
       {    
      if ( args.length != 1 )
      {
        System.out.println("Error -- usage is:  java Lab10 matdataN.txt");
        System.exit( 0 );
      }
    
        //Requirement #1: first int value: # of rows, second int value: # of cols
        File newFile = new File(args[0]); 
        Scanner in = new Scanner(newFile);
    
        int numRows = in.nextInt();
        int numCols = in.nextInt();
    
        //Requirement #2: declare two-d array of ints
        int[][] matrix;
        matrix = new int[numRows][numCols];
    
        //Requirement #3 & 4: read file one line at a time (nested for loops 
            //and nextInt()) and print
    
        for (int i = 0; i < numRows; i++)
        {
            for (int j = 0; j < numCols; j++)
            {
                matrix[i][j] = in.nextInt();
                System.out.print(matrix[i][j]+ " ");
            }
        System.out.println();
        }
    
        //Requirement #5: traverse each row and sum the values and display the sums
        int rowTotal = 0;
        for (int i = 0; i < numRows; i++)
        {
            rowTotal = 0;
            for (int j = 0; j < numCols; j++)
            {
                rowTotal += matrix[i][j];
            }
        System.out.println("Sum for row = " + rowTotal);
        }
    
        //Requirement #6: traverse each column and sum the values and display the sums
        int colTotal = 0;
        for (int i = 0; i < numRows; i++)
        {
            colTotal = 0;
            for (int j = 0; j < numCols; j++)
            {
                colTotal += matrix[j][i];
            }
        System.out.println("Sum for col = " + colTotal);
        }
    
        //Requirement #7: traverse the perimeter and sum the values and display the sum
    
        //sum bottom row matrix
        int perTotal = 0;
        for (int i = (numRows-1); i < numRows; i++)
        {
            perTotal = 0;
            for (int j = 0; j < numCols; j++)
            {
                perTotal += matrix[i][j];
            }
        }
    
        //sum + top row matrix
        for (int i = 0; i < numRows - (numRows-1); i++)
        {
            for (int j = 0; j < numCols; j++)
            {
                perTotal += matrix[i][j];
            }
        System.out.println("Sum of perimeter = " + perTotal);
        }
    
        // sum + first col middle
        for (int i = 1; i < (numRows-1); i++)
        {
            for (int j = 0; j < numCols - (numCols-1); j++)
            {
                perTotal += matrix[j][i];
            }
        System.out.println("Sum = " + perTotal);
        }
    
        // sum + last col middle
        for (int i = 1; i < (numRows-1); i++)
        {
            for (int j = (numCols-1); j < numCols; j++)
            {
                perTotal += matrix[j][i];
            }
        System.out.println(perTotal);
        }
    
       }
    

    I would be hugeeeeeely appreciative if anyone could help me total the middle of the first and last column (should be 2+2 and 8+8). Or if you have an altogether better way of finding the perimeter. Thanks in advance!

  • LaGrandMere
    LaGrandMere about 11 years
    In case there is only 1 line, you sum it twice to calculate perimeter ... Not sure what to do in this case, in my answer I considered to sum it only once with a if.
  • Martinsos
    Martinsos about 11 years
    If you are handling case when there is just one row, then you should also handle case when there is just one column