I've written a recursive method for fetching grid neighbours in a symmetrical 2-dimensional grid, the problem is that I've found myself duplicating the code more or less into an overload to prevent my list from re-initializing everytime the method calls on itself.
I'm guessing there are ways to get around this that doesn't involve code duplication. Any help is appreciated.
public List<Cell<int>> GetNeighbours(Cell<int> cell, Direction direction, int neighboursToGet)
{
var neighbours = new List<Cell<int>>();
if (neighboursToGet > 0)
{
int x = 0;
int y = 0;
Cell<int> neighbour;
switch (direction)
{
case Direction.Left:
x = -1;
break;
case Direction.Right:
x = 1;
break;
case Direction.Up:
y = -1;
break;
case Direction.Down:
y = 1;
break;
}
neighbour = cells[cell.Position.Row + y, cell.Position.Column + x];
neighbours.Add(neighbour);
GetNeighbours(neighbour, direction, neighboursToGet - 1, neighbours);
}
return neighbours;
}
public List<Cell<int>> GetNeighbours(Cell<int> cell, Direction direction, int neighboursToGet, List<Cell<int>> neighbours)
{
if (neighboursToGet > 0)
{
int x = 0;
int y = 0;
Cell<int> neighbour;
switch (direction)
{
case Direction.Left:
x = -1;
break;
case Direction.Right:
x = 1;
break;
case Direction.Up:
y = -1;
break;
case Direction.Down:
y = 1;
break;
}
neighbour = cells[cell.Position.Row + y, cell.Position.Column + x];
neighbours.Add(neighbour);
GetNeighbours(neighbour, direction, neighboursToGet - 1, neighbours);
}
return neighbours;
}