vkaleri vkaleri - 7 months ago 18
Java Question

Trying to find the closest available spot in a 2D array

I am trying to find the closest available seat.However ,I did try something but i could not find it ,so far after some formatting i came back to my star position.Any suggestions.!

public void nextFree(String seats) {
int colA = 0;
int rowA = Integer.parseInt(seats.substring(1, 2));
int newColB = 0;
int newRowB = 0;

if (seats.equalsIgnoreCase("a")) {
colA = 1;
} else if (seats.equalsIgnoreCase("b")) {
colA = 2;
} else if (seats.equalsIgnoreCase("c")) {
colA = 3;
} else {
colA = 4;
}

for (int i = 0; i < this.table.length; i++) {
for (int k = 0; k < this.table.length; k++) {
if (table[i][k] == "XX") {
newRowB = i;
newColB = k;
}
}
System.out.print("The seat " + colA + rowA + " is not available! The next availale is " + newColB + newRowB);
}

}

Answer
public void nextFree(String seats) {
    int colA = 0;
    int rowA = Integer.parseInt(seats.substring(1, 2));
    int newColB = 0;
    int newRowB = 0;
    int distance = -1;
    //Would recommend changing this to a switch statement, might lake it clearer
    if (seats.equalsIgnoreCase("a")) {
        colA = 1;
    } else if (seats.equalsIgnoreCase("b")) {
        colA = 2;
    } else if (seats.equalsIgnoreCase("c")) {
        colA = 3;
    } else {
        colA = 4;
    }

    for (int i = 0; i < table.length; i++) {
        for (int k = 0; k < table[i].length; k++){
            //Calculating current distance away from our chair
            //This assumes i is the column and k is the row, you may need to swap those values around
            int curDistance = Math.abs(i-colA) + Math.abs(k-rowA);
            //If the seat is free and the distance hasn't been set or the current distance is less than the previous distance
            if (table[i][k].equals("--") && (distance == -1 || distance > curDistance) {
                //Found a closer seat
                newRowB = i;
                newColB = k;
                distance = curDistance;
            }
        }
    }
    //Moved this out the for loop, it shouldn't have been inside
    System.out.print("The seat " + colA + rowA + " is not available! The next availale is " + newColB + newRowB);
}

Using the Manhattan distance as detailed here

This code does not assume you care about rows, if a seat is behind the current seat and is available, it could be considered closer than one in the same row

The Manhattan distance gives the following results when compared to the master seat:

            Row   Seat  Distance
Master       1     1       0
Next to      1     2       1
Behind       2     1       1
In front     0     1       1
Diagonal     2     2       2

Proof that it's working for me:

Taking seats

Results