HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

Can I simplify this recursive grid search?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thiscangridsearchrecursivesimplify

Problem

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> GetNeighbours(Cell cell, Direction direction, int neighboursToGet)
{
var neighbours = new List>();

if (neighboursToGet > 0)
{
int x = 0;
int y = 0;
Cell 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> GetNeighbours(Cell cell, Direction direction, int neighboursToGet, List> neighbours)
{
if (neighboursToGet > 0)
{
int x = 0;
int y = 0;
Cell neighbour;

switch (direction)
{
case Direction.Left:
x = -1;
break;
case Direction.Right:
x = 1;
break;
case Direction.Up:
y

Solution

It seems to me that most of the body of the first GetNeighbours is extraneous. Wouldn't this be enough ?

public List> GetNeighbours(Cell cell, Direction direction, int neighboursToGet)
{
    var neighbours = new List>();

    GetNeighbours(cell, direction, neighboursToGet, neighbours);

    return neighbours;
}


Also, it is redundant to accept neighbours as a read/write parameter and to return it. However, if you are going to do it, you could as well write:

public List> GetNeighbours(Cell cell, Direction direction, int neighboursToGet)
{
    return GetNeighbours(cell, direction, neighboursToGet, new List>());
}

Code Snippets

public List<Cell<int>> GetNeighbours(Cell<int> cell, Direction direction, int neighboursToGet)
{
    var neighbours = new List<Cell<int>>();

    GetNeighbours(cell, direction, neighboursToGet, neighbours);

    return neighbours;
}
public List<Cell<int>> GetNeighbours(Cell<int> cell, Direction direction, int neighboursToGet)
{
    return GetNeighbours(cell, direction, neighboursToGet, new List<Cell<int>>());
}

Context

StackExchange Code Review Q#48790, answer score: 6

Revisions (0)

No revisions yet.