Good way of finding the sum of the neighboring values in a 2d array. I need to find the sum of all neighboring values at an index position.
E.g. int[,] array = new int[3, 4] { { 0, 1, 2, 3 }, { 4, 5, 6, 7 }, { 8, 9, 10, 11 } };
Here neighbors of 5.
I.e. [1.1] will be [0,0] + [0,1] + [0,2] + [1,0] + [1,2] + [2,0] + [2,1] + [2,2]
And Sum will be 40.
- public class SumOfNeibours
- {
- int[, ] array = new int[3, 4]
- {
- {
- 0, 1, 2, 3
- }, {
- 4, 5, 6, 7
- }, {
- 8, 9, 10, 11
- }
- };
- public void GetSumOfNeibours()
- {
- int newval = 0;
- for (int i = 0; i < array.Length; i++)
- {
- var x = i / 4;
- var y = i % 4;
- var startX = x - 1 < 0 ? 0 : x - 1;
- var endX = x + 1 > 2 ? 2 : x + 1;
- var startY = y - 1 < 0 ? 0 : y - 1;
- var endY = y + 1 > array.GetLength(0) ? array.GetLength(0) : y + 1;
-
- for (int z = startX; z <= endX; z++)
- {
- for (int j = startY; j <= endY; j++)
- {
- if (x == z && y == j)
- {
- continue;
- }
- var v = array[z, j];
- Console.WriteLine(array[z, j] + " ");
- newval += array[z, j];
- }
- }
- Console.WriteLine("\n ");
- Console.WriteLine("Sum is" + newval);
- newval = 0;
- }
- }
- }