Created
March 21, 2020 11:29
-
-
Save ApprenticeGC/08753aac0db21ad47d3a643a49fac9e1 to your computer and use it in GitHub Desktop.
Get neighbors of one particular cell defined by x and y index
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public int[] GetStatusOfCellNeighbors(int xIndex, int yIndex) | |
{ | |
// Use x from left to right, y from bottom to top | |
// 2,0 2,1, 2,2 | |
// 1,0 1,1, 1,2 | |
// 0,0 0,1, 0,2 | |
(int, int)[] GetIndicesOfNeighbors() | |
{ | |
return new (int, int)[] | |
{ | |
(-1, +1), (0, +1), (+1, +1), | |
(-1, 0), /* self */ (+1, 0), | |
(-1, -1), (0, -1), (+1, -1) | |
}; | |
} | |
var neighborIndexPairs = GetIndicesOfNeighbors(); | |
// This may not always be count of 8 as there are cases near boundary | |
// So using dynamic list instead of array | |
var statusOfNeighbors = new List<int>(); | |
for (var i = 0; i < neighborIndexPairs.Length; ++i) | |
{ | |
var (x, y) = neighborIndexPairs[i]; | |
// Check if the index of neighbor is valid | |
var adjustedXIndex = x + xIndex; | |
var adjustedYIndex = y + yIndex; | |
if (adjustedXIndex < 0 || adjustedYIndex < 0) | |
{ | |
// adjustedXIndex means out of left board boundary | |
// adjustedYIndex means out of bottom board boundary | |
} | |
else if (adjustedXIndex >= width || adjustedYIndex >= height) | |
{ | |
// Use equal because it is 0 base | |
// adjustedXIndex means out of right board boundary | |
// adjustedYIndex means out of up board boundary | |
} | |
else | |
{ | |
// Valid index | |
var gridCell = _gridCells[adjustedXIndex, adjustedYIndex]; | |
var status = gridCell.Status; | |
statusOfNeighbors.Add(status); | |
} | |
} | |
// However at returning, need to return array to satisfy return type | |
return statusOfNeighbors.ToArray(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment