/*
| a b c d e f g h-------------------------------------
1| a1 b1 c1 d1 e1 f1 g1 h1
2| a2 b2 c2 d2 e2 f2 g2 h2
3| a3 b3 c3 d3 e3 f3 g3 h3
4| a4 b4 c4 d4 e4 f4 g4 h4
5| a5 b5 c5 d5 e5 f5 g5 h5
6| a6 b6 c6 d6 e6 f6 g6 h6
7| a7 b7 c7 d7 e7 f7 g7 h7
8| a8 b8 c8 d8 e8 f8 g8 h8
*/
//The maximum moves for queen to reach any position in the chessboard is 2
//a1-a1-> 0 moves
//b1-a1-> 1 moves
//a1-b3-> 2 moves
package com.queenmoves;
import static java.lang.Math.abs;
import static java.lang.System.exit;
import java.util.Scanner;
/**
*
* @author anuz
*/
public class Program {
public static void main(String[] args) {
String firstPosition, secondPosition;
int moves;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a position of queen:");
firstPosition = scanner.nextLine().toLowerCase().trim();
System.out.print("Enter any postion:");
secondPosition = scanner.nextLine().toLowerCase().trim();
moves=queenMoves(firstPosition.toCharArray(),secondPosition.toCharArray());
System.out.println("No. of Moves:"+moves);
}
private static int queenMoves(char[] arrayOfFirstPosition, char[] arrayOfSecondPosition) {
int noOfMoves=0;
//validate input [a1...h8]
if(arrayOfFirstPosition[0] < 'a' || arrayOfFirstPosition[0]>'h' || arrayOfFirstPosition[1] < '1' || arrayOfFirstPosition[1]>'8' ||
arrayOfSecondPosition[0] < 'a' || arrayOfSecondPosition[0]>'h' || arrayOfSecondPosition[1] < '1' || arrayOfSecondPosition[1]>'8'){
System.out.println("Invalid input");
exit(0);
}
if(arrayOfFirstPosition[0]==arrayOfSecondPosition[0] && arrayOfFirstPosition[1]==arrayOfSecondPosition[1]){
noOfMoves=0;
}else if(arrayOfFirstPosition[0]==arrayOfSecondPosition[0] || arrayOfFirstPosition[1]==arrayOfSecondPosition[1] ||
abs(arrayOfFirstPosition[0]-arrayOfSecondPosition[0])==abs(arrayOfFirstPosition[1]-arrayOfSecondPosition[1])){
noOfMoves=1;
}else{
noOfMoves=2;
}
return noOfMoves;
}
}
_________________________________________
No comments:
Post a Comment