Chess Board Cell Color

Chess Board Cell Color

### Given two cells on the standard chess board, determinine wheather they have the same color or not —

function chessBoardCellColor(cell1, cell2) {
  const board = {
    "A":1,
    "B":2,
    "C":3,
    "D":4,
    "E":5,
    "F":6,
    "G":7,
    "H":8
  };

  const total_1 = (board[cell1[0]] + parseInt(cell1[1])) % 2;
  const total_2 = (board[cell2[0]] + parseInt(cell2[1])) % 2;

  return total_1  === total_2 ;


}

console.log(chessBoardCellColor('A1','C3')) true
console.log(chessBoardCellColor('A1','H3')) false


♟️ Chess Board Cell Color

⚙️ Implementation Details

📌 Parameters

cell1 (String): The first chessboard cell to compare (e.g., ‘A1’).

cell2 (String): The second chessboard cell to compare (e.g., ‘C3’).

🔍 Step-by-Step Logic

Create a Board Mapping: Define an object called board that assigns numerical values to chessboard columns from A to H, ranging from 1 to 8.

Calculate the First Cell: Access the column letter using cell1[0] and the row number using parseInt(cell1[1]). Add these values together and use the modulo operator (% 2) to determine the cell’s color parity.

Calculate the Second Cell: Apply the same calculation to cell2 by extracting its column and row values, adding them together, and calculating the remainder when divided by 2.

Determine Cell Color: The modulo operation produces either 0 or 1, representing the two alternating chessboard colors.

Compare the Results: Use the strict equality operator (===) to compare the parity values of both cells.

Return the Result:

If both values are equal, return true because the cells have the same color.

If the values are different, return false because the cells have different colors.

🧪 Examples

Input

Output

chessBoardCellColor(‘A1’, ‘C3’)

true

chessBoardCellColor(‘A1’, ‘H3’)

false

💡 Key Takeaway

Chessboard cells alternate between two colors. By adding the numerical column and row positions and calculating their remainder using the modulo operator (% 2), we can determine the color parity of each cell.

If both cells have the same parity, they have the same color; otherwise, they have different colors.

comments powered by Disqus