Chess Knight Moves

Description:

Given a position of a knight on the standard chessboard, find the number of different moves the knight can perform.

The knight can move to a square that is two squares horizontally and one square vertically, or two squares vertically and one square horizontally away from it. The complete move therefore looks like the letter L. Check out the image below to see all valid moves for a knight piece that is placed on one of the central squares.

Example

  • For cell = "a1", the output should be
    chessKnightMoves(cell) = 2.

  • For cell = "c2", the output should be
    chessKnightMoves(cell) = 6.

Input/Output

  • [time limit] 3000ms (java)
  • [input] string cell

    String consisting of 2 letters – coordinates of the knight on an 8 × 8 chessboard in chess notation.

  • [output] integer

Tests:
Solution(Java):

int chessKnightMoves(String cell) {
    int x = cell.charAt(0) % 97,
    y = +cell.charAt(1) - '0' - 1;
    int c = 0;
    for (int dx = -2; dx <= 2; dx++)
        for (int dy = -2; dy <= 2; dy++) {
            if (Math.abs(dx * dy) == 2)
                if (isValid(x + dx, y + dy))
                    c++;
        }
    return c;
}
private static boolean isValid(int x, int y) {
    return x >= 0 && x <= 7 && y >= 0 && y <= 7;
}

 

Bishop And Pawn

Description:

Given the positions of a white bishop and a black pawn on the standard chess board, determine whether the bishop can capture the pawn in one move.

The bishop has no restrictions in distance for each move, but is limited to diagonal movement. Check out the example below to see how it can move:

Example

  • For bishop = "a1" and pawn = "c3", the output should be
    bishopAndPawn(bishop, pawn) = true.

  • For bishop = "h1" and pawn = "h3", the output should be
    bishopAndPawn(bishop, pawn) = false.

Input/Output

  • [time limit] 3000ms (java)
  • [input] string bishop

    Coordinates of the white bishop in the chess notation.

  • [input] string pawn

    Coordinates of the black pawn in the same notation.

  • [output] boolean

    true if the bishop can capture the pawn, false otherwise.

Tests:
Solution(Java):

boolean bishopAndPawn(String bishop, String pawn) {
    class Parser {
        int getX(char pos) {
            return pos - 'A';
        }

        int getY(char pos) {
            return pos - '1';
        }
    }
    Parser p = new Parser();

    int x1 = p.getX(bishop.charAt(0)),
        y1 = p.getY(bishop.charAt(1)),
        x2 = p.getX(pawn.charAt(0)),
        y2 = p.getY(pawn.charAt(1));

    if (x1 + y1 == x2 + y2 || x1 - y1 == x2 - y2) {
        return true;
    }

    return false;
}