I am trying to learn Java by doing some (easy) ACM ICPC problems. The problem consist to check if the knight in a chess game can move from a point A(r1, c1)
to B(r2, c2)
with one move only.
package dalia;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class Dalia {
static int[] moves = { -1, 2, -1, -2, 1, 2, 1, -2, -2, 1, -2, -1, 2, 1, 2, -1 };
public static void main(String[] args) throws IOException {
File fin = new File("./dalia.in");
knight(fin);
}
private static void knight(File fin) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(fin))) {
String line;
// Read the number of cases.
int numberOfCases = Integer.parseInt(br.readLine());
int[] cord = new int[5];
String[] parts;
int i = 0;
// Solve each case
while ((line = br.readLine()) != null && i < numberOfCases) {
// Split the line to array of integer
parts = line.split(" ");
for (int j = 0; j < 5; j++) {
cord[j] = Integer.parseInt(parts[j]);
}
// Print case number
i++;
System.out.print("Case " + i + ": ");
// Check if the knight can move
if (validMove(cord[0], cord[1], cord[2], cord[3], cord[4]))
System.out.println("YES");
else
System.out.println("NO");
}
br.close();
}
}
private static boolean validMove(int n, int r1, int c1, int r2, int c2) {
// Return True if the knight can move from (r1, c1) to (r2, c2) in one
// move
for (int i = 0; i < moves.length; i = i + 2) {
if (r1 == r2 + moves[i] && c1 == c2 + moves[i + 1] && stillInTheBoard(n, r2, moves[i])
&& stillInTheBoard(n, c2, moves[i + 1]))
return true;
}
return false;
}
private static boolean stillInTheBoard(int n, int x1, int x2) {
// Check if the knight still in the board after making the move
return (1 <= x1 + x2 && x1 + x2 <= n);
}
}
Example:
Input:
2
4 1 2 2 4
5 1 1 3 3
Output:
Case 1: YES
Case 2: NO
Where the first number is n
, the number of block in the Chess board (in the normal Chess board n = 8).
I'm looking for a review in terms of best practices, things I should or shouldn't do, or things I should do in another way.