I created this short code as an exercise to learn and practice my OOPS. The aim is - given a string of points as x1,y1,x2,y2... figure out how many of them lie inside a given rectangle.
Can anyone please point out what things I can improve in this code design and best practices wise.
public class Solution{
private String points;
public Solution(String points) {
this.points = points;
}
@Override
public String checkPointsInRectangle() {
String[] numbers = points.split(", ");
List<Point> pointList = getPointsList(numbers);
SortedSet<Point> pointsByX =
new TreeSet<>(Comparator.comparingInt((Point p) -> p.x)
.thenComparingInt((Point p) -> p.y));
SortedSet<Point> pointsByY =
new TreeSet<>(Comparator.comparingInt((Point p) -> p.y)
.thenComparingInt((Point p) -> p.x));
pointsByX.addAll(pointList);
pointsByY.addAll(pointList);
Rectangle rect = new Rectangle(-3,7,-10,10);
Set<Point> result = getPointsInRect(rect, pointsByX, pointsByY);
StringBuilder joined = new StringBuilder();
for(Point s : result){
joined.append(s.x);
joined.append(s.y);
}
return joined.toString();
}
List<Point> getPointsList(String [] points){
List<Point> result = new ArrayList<>();
for(int i=0;i< points.length-1;i++) {
if (i % 2 == 0) {
Point point = new Point(Integer.parseInt(points[i]), Integer.parseInt(points[i + 1]));
result.add(point);
}
}
return result;
}
Set<Point> getPointsInRect(Rectangle rect, SortedSet<Point> pointsByX, SortedSet<Point> pointsByY) {
Point minXMinY = new Point(rect.x0, rect.y0);
Point maxXMaxY = new Point(rect.x1, rect.y1);
Set<Point> pointsX = pointsByX.subSet(minXMinY, maxXMaxY);
Set<Point> pointsY = pointsByY.subSet(minXMinY, maxXMaxY);
Set<Point> rectPoints = new HashSet<>(pointsY);
rectPoints.retainAll(pointsX);
return rectPoints;
}
}
public class Point {
final int x; // made final so that user provided input is immutable.
final int y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
EDIT Added the Rectangle class as well
package dummy;
public class Rectangle {
final int x0,x1,y0,y1;
public Rectangle(int x0, int x1, int y0, int y1) {
this.x0 = x0;
this.x1 = x1;
this.y0 = y0;
this.y1 = y1;
}
}