I've recently implemented a Wilson's Algorithm for maze generation. This problem however could also be extended to things such as snake, or some other simple AIs.

The problem is as follows:

> 
> Blue Node -> Previous nodes
> 
> 
> Red Node -> Current node
> 
> 
> Black Line -> Wall
> 
> 
> ![Figure 1](https://i.stack.imgur.com/D4TBu.png)
> 
> 
> In this case, we can analyze each of the 4 possible directions: up,
>  right, down and left.
> 
> 
> 1. Up - Not available, since the last move was down (reversing itself)
> 2. Right - Not available, since there is a wall directly to the right
> 3. Down - Available
> 4. Left - Available
> 
> 
> From here we can see that should it move down, then the same
>  availability will occur. If it should move left: up, left and down
>  would then be available.
> 
> 
> 

The way I have implemented this is as follows:

```
private int nextDirection(final int i, final int j, final int rowLimit, final int columnLimit, final int previous) {
    boolean up = true;
    boolean right = true;
    boolean down = true;
    boolean left = true;
    if (i == 0) {
        up = false;
    } else if (i == rowLimit) {
        down = false;
    }
    if (j == 0) {
        left = false;
    } else if (j == columnLimit) {
        right = false;
    }
    switch (previous) {
        case DIRECTION_UP:
            down = false;
            break;
        case DIRECTION_DOWN:
            up = false;
            break;
        case DIRECTION_RIGHT:
            left = false;
            break;
        case DIRECTION_LEFT:
            right = false;
    }
    final ArrayList<Integer> list = new ArrayList<>(4);
    if (left) {
        list.add(DIRECTION_LEFT);
    }
    if (right) {
        list.add(DIRECTION_RIGHT);
    }
    if (down) {
        list.add(DIRECTION_DOWN);
    }
    if (up) {
        list.add(DIRECTION_UP);
    }
    return list.get(random.nextInt(list.size()));
}

```

Where:

* `i` - row of current node
* `j` - column of current node
* `rowLimit` - row count minus one
* `columnLimit` - column count minus one
* `previous` - previous direction
* `random` - `java.util.Random instance`

Now, I highly doubt this is the most efficient solution. However it is the least - well - troublesome. The others I have used are just a large amount of `if` statements considering every possible case.

However, neither of these solutions - at least how I see them - are efficient enough. Due to this and what Knuth once said, I went for readability. The main problem is, this has become a bottleneck in the calculation speeds.

Question:

Is there a way to better calculate the available directions? And therefore a better way to select a random direction.

Sides notes:

```
DIRECTION_UP    = 0x01;
DIRECTION_RIGHT = 0x02;
DIRECTION_DOWN  = 0x04;
DIRECTION_LEFT  = 0x08;

```

These can be changed to whatever value needed.