Sum neighbors of a given index in a bi dimensional matrix in Swift
I was solving this problem a couple days ago and I decided to post it here, so maybe I can help someone facing something similar.
Basically given a two dimensions matrix of numbers, we have to sum the value of the neighbors of an also given index. The index will be constituted of a line and column. Let's see an example of matrix that could be used in our algorithm.
This matrix shown is a possible example. It contains 10 lines and 4 columns. In order to test the algorithm I create a simple function to fill a empty matrix with random numbers, as is possible to see below:
Now that we have the matrix ready to be used by our algorithm, we can actually work on it. The first thing to analyse would be who's the neighbors of a given index, let's say index = (line: 5, column: 3). Analysing the figure posted before, or just using our imagination will notice that the neighbors are:
line 4, column 2
line 4, column 3
line 4, column 4
line 5, column 2
line 5, column 4
line 6, column 2
line 6, column 3
line 6…