Skip to content

Instantly share code, notes, and snippets.

@le-doude
Last active August 29, 2015 14:02
Show Gist options
  • Save le-doude/7e28fa104e51313fbfd0 to your computer and use it in GitHub Desktop.
Save le-doude/7e28fa104e51313fbfd0 to your computer and use it in GitHub Desktop.
Solves the problem: "Given an origin and a destination on an empty chessboard, count how many moves are necessary for the rook to go from one to the other."
package org.rooksolver;
/**
* Created by le-doude on 14/06/16.
*/
public class Solver {
static final byte[][] moves = new byte[64][64];
static final boolean[] isBlackSquare = {
true, false, true, false, true, false, true, false,
false, true, false, true, false, true, false, true,
true, false, true, false, true, false, true, false,
false, true, false, true, false, true, false, true,
true, false, true, false, true, false, true, false,
false, true, false, true, false, true, false, true,
true, false, true, false, true, false, true, false,
false, true, false, true, false, true, false, true,
};
static {
for (int i = 0; i < 64; i++) {
moves[i][i] = 0; //same square
for (int j = i + 1; j < 64; j++) {
if (moves[i][j] == 0) {
if (isBlackSquare[i] != isBlackSquare[j]) {//is on same color
moves[i][j] = moves[j][i] = -1; //not reachable
} else {
moves[i][j] = moves[j][i] = (byte) (isOnDiagonal(i, j) ? 1 : 2); //reachable since on same color
}
}
}
}
}
//i always lesser than j
private static boolean isOnDiagonal(int i, int j) {
for (int k = i; k < 64; k+=7) {
if(isBlackSquare[j] != isBlackSquare[k]) {
break; //we have gone over the border.
}
if (k == j) {
return true;
}
}
for (int k = i; k < 64; k += 9) {
if(isBlackSquare[j] != isBlackSquare[k]) {
break; //we have gone over the border.
}
if (k == j) {
return true;
}
}
return false;
}
public static int countMovesForRook(int from, int to) {
if (0 <= from && from < 64 && 0 <= to && to < 64) {
return moves[from][to];
} else {
return -1;
}
}
public static int countMovesForRook(int X, int Y, int x, int y) {
if (0 <= X && X < 8 && 0 <= Y && Y < 8 && 0 <= x && x < 8 && 0 <= y && y < 8) {
return countMovesForRook((X * 8) + Y, (x * 8) + y);
} else {
return -1;
}
}
}
@le-doude
Copy link
Author

This was a problem that was given to me during an interview at a very important company. On the moment I had a pure head-fart and couldn't even think of a most basic solution.
Actually the problem is very easy once you identify all 4 possible answers. Good training.

@le-doude
Copy link
Author

NB: isBlackSquare can be done with the function ((x / 8) % 2) == (x % 2)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment