java - How to sum a cell and the surround cells within a matrix -


i want sum cells. mean, surrounding cells. add cell call upon , add value values around it. have far.

import java.util.arrays; import static java.lang.system.*;  public class matrixsummingrunner {     public static void main(string args[]) {          int[][] mat = { { 0, 1, 0, 0, 0, 1, 0 }, { 1, 8, 4, 3, 4, 5, 1 },                 { 0, 2, 7, 8, 9, 8, 0 }, { 0, 6, 7, 6, 2, 5, 0 },                 { 0, 6, 7, 8, 9, 5, 0 }, { 1, 5, 4, 3, 2, 3, 1 },                 { 0, 1, 0, 0, 0, 1, 0 } };         out.println("sum of given values, @ {4,2} , values around it"                 + matrixsumming(mat, 4, 2));         out.println("sum of given values, @ {3,3} , values around it"                 + matrixsumming(mat, 3, 3));         out.println("sum of given values, @ {5,4} , values around it"                 + matrixsumming(mat, 5, 4));         out.println(tostring(mat));     } } 

that's runner, , thought work.

import java.util.*;  public class matrixsumming {     private int[][] m = { { 4, 2 }, { 3, 3 }, { 5, 4 } }; // load in matrix                                                           // values      public int sum(int[][] mat, int x, int y) {         int sum = 0;         (int item : mat) {             sum = getvalueat(x, y) + getvalueat(x++, y) + getvalueat(x--, y)                     + getvalueat(x--, y++) + getvalueat(x--, y--)                     + getvalueat(x++, y++) + getvalueat(x++, y--);         }          return sum;     } } 

apparently didn't work. it's counting them individual variables, causing massive problem me...

this code doesn't make sense:

   for(int item : mat)     {         sum=getvalueat(x,y) + getvalueat(x++,y) + getvalueat(x--,y) + getvalueat(x--,y++) + getvalueat(x--,y--) + getvalueat(x++,y++) + getvalueat(x++,y--);     } 

for starters, you're modifying x , y variables inside of function. instead, use +1 , -1 appropriate.

secondly, you've never defined sum variable, , you're overwriting value every time loop increments. instead, need add values existing sum previous times loop has fired.

here's example of how might figure out sum array:

int sum = 0; for(int x : array){    sum = sum+x; } system.out.println(sum); 

Comments

Popular posts from this blog

java - Custom OutputStreamAppender not run: LOGBACK: No context given for <MYAPPENDER> -

java - UML - How would you draw a try catch in a sequence diagram? -

c++ - No viable overloaded operator for references a map -