avocadoLambda
avocadoLambda

Reputation: 1046

How to find in which positions can collide two queen. (Chess 8x8)

I wrote a code that finds which two queen positions can collide. Can it be done better and with less code:

import java.util.Scanner;

class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int x1 = scanner.nextInt();
        int y1 = scanner.nextInt();
        int x2 = scanner.nextInt();
        int y2 = scanner.nextInt();

        if (x1 == x2 || y1 == y2) {
            System.out.println("YES");
        }
        else if (x1 == x2 || y1 == y2) {
            System.out.println("YES");
        }
        else if (Math.abs(x1 - x2) == Math.abs(y1 - y2)) {
            System.out.println("YES");
        }else{
            System.out.println("NO");
        }
    }
}

Upvotes: 0

Views: 76

Answers (2)

Thomas Bitonti
Thomas Bitonti

Reputation: 1234

There is a duplicate check in the implementation: The second if block is the same as the first if block.

public boolean checkQueens_v1(int x1, int y1, int x2, int y2) {
    if ( (x1 == x2) || (y1 == y2) ) {
        return true;
    } else if ( Math.abs(x1 - x2) == Math.abs(y1 - y2) ) {
        return true;
    } else{
        return false;
    }
}

The following is an alternative:

public boolean checkQueens_v2(int x1, int y1, int x2, int y2) {
    int xdiff = x1 - x2;
    if ( xdiff == 0 ) {
        return true;
    }
    int ydiff = y1 - y2;
    if ( ydiff == 0 ) {
        return true;
    }
    if ( Math.abs(xdiff) == Math.abs(ydiff) ) {
        return true;
    }
    return false;
}

Which is smaller / faster is hard to say:

The first test has three comparisons and two subtractions. The second test has two comparisons against zero, one comparison, and two subtractions.

But, the second test does its subtractions more often than the first test.

Upvotes: 1

Harshal Parekh
Harshal Parekh

Reputation: 6017

if (x1 == x2 || y1 == y2 || (Math.abs(x1 - x2) == Math.abs(y1 - y2))) {
    System.out.println("YES");
} else {
    System.out.println("NO");
}

else if (x1 == x2 || y1 == y2) {
    System.out.println("YES");
}

This condition is redundant.


else if (Math.abs(x1 - x2) == Math.abs(y1 - y2)) {
    System.out.println("YES");
}

This can be merged with the previous condition since it has the same output.

Upvotes: 1

Related Questions