Skip to content

Bishop and Pawn

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:

image credit : CodeSignal

Example

  • For bishop = "a1" and pawn = "c3", the output should be

    bishop_and_pawn(bishop, pawn) = true
    image credit : CodeSignal
  • For bishop = "h1" and pawn = "h3", the output should be

    bishop_and_pawn(bishop, pawn) = false
    image credit : CodeSignal

Input/Output

  • [input] string bishop

    Coordinates of the white bishop in the chess notation.

    Guaranteed constraints:bishop.length = 2, 'a' ≤ bishop[0] ≤ 'h', 1 ≤ bishop[1] ≤ 8.

  • [input] string pawn

    Coordinates of the black pawn in the same notation.

    Guaranteed constraints:pawn.length = 2, 'a' ≤ pawn[0] ≤ 'h', 1 ≤ pawn[1] ≤ 8.

Solution

py
def bishop_and_pawn(bishop, pawn):
    return (
        bishop[0] != pawn[0]
        and
        bishop[1] != pawn[1]
        and
        (
            (ord(bishop[0]) + int(bishop[1])) % 2
            ==
            (ord(pawn[0]) + int(pawn[1])) % 2
        )
    )


print(bishop_and_pawn('a1', 'b1'))
print(bishop_and_pawn('a1', 'c3'))
print(bishop_and_pawn('g1', 'f3'))
print(bishop_and_pawn('h1', 'h3'))
js
function bishopAndPawn(bishop, pawn) {
  return Math.abs(bishop.charCodeAt(0) - pawn.charCodeAt(0)) == Math.abs(bishop.charCodeAt(1) - pawn.charCodeAt(1));
}

console.log(bishopAndPawn('a1', 'b1'));
console.log(bishopAndPawn('a1', 'c3'));
console.log(bishopAndPawn('g1', 'f3'));
console.log(bishopAndPawn('h1', 'h3'));

my thoughts are neither my employer's nor my wife's