Point Quadrant (Record Pattern)
Problem
Read two integers x and y: a point. Print Q1 if both are positive, Q2 if x is negative and y positive, Q3 if both are negative, Q4 if x is positive and y negative, and axis if the point is on an axis (x or y is 0).
Constraints
- |x|, |y| <= 10^9
Examples
Input
3 4
Output
Q1
Input
0 5
Output
axis
Solutions
The old way needs a class with fields, a constructor and getters, and then if-else code that calls the getters.
/*
* Problem : Find the quadrant.
* Input : Two integers x and y.
* Output : Q1, Q2, Q3, Q4 or axis.
* Approach: Class and getters.
* Time : O(1)
* Space : O(1)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// Step 1: A normal class with two fields and two getters.
static final class Point {
private final long x;
private final long y;
Point(long x, long y) {
this.x = x;
this.y = y;
}
long getX() {
return x;
}
long getY() {
return y;
}
}
// This method solves the task. It receives the input and returns the answer.
static String solve(long a, long b) {
// Step 2: Read the values through the getters, then choose the quadrant.
Point point = new Point(a, b);
if (point.getX() == 0 || point.getY() == 0) {
return "axis";
}
if (point.getX() > 0) {
return point.getY() > 0 ? "Q1" : "Q4";
}
return point.getY() > 0 ? "Q2" : "Q3";
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
long a = scanner.nextLong();
long b = scanner.nextLong();
System.out.println(solve(a, b));
}
}
Hints (1)
- Which quadrant has a negative x and a positive y?