ChessBoard
The chessboard has 64 squares, 8 rows and 8 columns. Each row is labelled from 1 to 8 and each column as a to h. A square is the intersection of a row and a column, like 2c is the intersection of row 2 and column c. Positioning a pawn to a start square, you need to find out where it will be the end square after moving it R times (rows) vertically to the top and C times (columns) horizontally to the right. If during the moves the pawn reaches the end of the board, it will start again from the opposite direction like examples below.
Input: string startPosition, number rows, number columns
Output : string endPosition
Examples
Input:
startPosition: 2b, rows: 3, columns: 2
Output: 5d
Input:
startPosition: 5h, rows: 11, columns: 25
Output: 8a
Code
public class ChessBoard {
/**
* function findEndPosition
* @param startposition
* @param rows
* @param columns
* @return
*
* finds the end position of the pawn given start position in a chess board
* and number of rows and columns moved
*
*/
public static String findEndPosition(String startposition, int rows, int columns) {
String[] chessColumns = {"a","b","c","d","e","f","g","h"};
String endPosition = "";
int startRow = startposition.charAt(0) - '0';
String startColumn = String.valueOf(startposition.charAt(1));
int index = 0;
for (int i = 0;i < chessColumns.length; i++) {
if (chessColumns[i].equalsIgnoreCase(startColumn)) {
index = i;
break;
}
}
int endRow = startRow + rows;
int endColumn = ++index + columns;
// checking whether during the moves the pawn reaches the end of the board,
// it will start again from the opposite direction.
if (!isValidSquare(endRow, endColumn)) {
endRow = endRow % 8 ;
endColumn = endColumn % 8;
if (endRow == 0)
endRow = 8;
if (endColumn == 0)
endColumn = 8;
}
String column = chessColumns[--endColumn];
endPosition += String.valueOf(endRow) + column;
return endPosition;
}
public static void main(String[] args) {
// calling the function to find the end position
// given start position, number of row and columns moved
// String currentPosition = findEndPosition("5h", 11, 25);
String currentPosition = findEndPosition("2b", 3, 2);
System.out.println("Current Position is: "+ currentPosition);
}
// Check if the coordinates are within the valid chessboard range
private static boolean isValidSquare(int row, int column) {
return row >= 1 && row <= 8 && column >= 1 && column <= 8;
}
}
Comments
Post a Comment