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;
}

 

Advertisements

One thought on “Bishop And Pawn

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s