I have to determine if an N sized list of coordinates defines a closed, exact rectangle.
I start with the question "How do I check if a list of coordinates is in the shape of a rectangle?"
The answer is:
- First and last element in
cordX
andcordY
have to be equal. - Difference between another key should be equal to 1.
- Value for key <1:size-2> has to be
const
.
Could you tell me if this is elegant and efficient code?
public class BoardPosition {
private int x;
private int y;
public int getX() {
return x;
}
void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
void setY(int y) {
this.y = y;
}
public BoardPosition(int pX, int pY) {
y = pY;
x = pX;
}
}
private boolean checkifIsRectangle(ArrayList<BoardPosition> lettersPosition) {
TreeMap<Integer, Integer> cordsX = new TreeMap<Integer, Integer>();
TreeMap<Integer, Integer> cordsY = new TreeMap<Integer, Integer>();
for (BoardPosition b : lettersPosition) {
if (!cordsX.containsKey(b.getX())) cordsX.put(b.getX(), 1);
else {
cordsX.put(b.getX(), cordsX.get(b.getX()) + 1);
}
if (!cordsY.containsKey(b.getY())) cordsY.put(b.getY(), 1);
else {
cordsY.put(b.getY(), cordsY.get(b.getY()) + 1);
}
}
boolean xIsValid = true;
boolean yIsValid = true;
//1
if (cordsX.values().toArray()[0] != cordsX.values().toArray()[cordsX.values().toArray().length - 1])
xIsValid = false;
if (cordsY.values().toArray()[0] != cordsY.values().toArray()[cordsY.values().toArray().length - 1])
yIsValid = false;
//2
int xKeyTest = -1;
for (Integer i : cordsX.keySet()) {
if (xKeyTest == -1) {
xKeyTest = i;
continue;
}
if ((i - xKeyTest) != 1) {
xIsValid = false;
break;
}
xKeyTest = i;
}
int yKeyTest = -1;
for (Integer i : cordsY.keySet()) {
if (yKeyTest == -1) {
yKeyTest = i;
continue;
}
if ((i - yKeyTest) != 1) {
yIsValid = false;
break;
}
yKeyTest = i;
}
//3
ArrayList<Integer> xValueArray = new ArrayList<Integer>(cordsX.values());
int xTestValue = -1;
for (int i = 1; i < xValueArray.size() - 2; i++) {
if (xTestValue == -1) {
xTestValue = xValueArray.get(i);
continue;
}
if (xTestValue != xValueArray.get(i)) {
xIsValid = false;
break;
}
}
ArrayList<Integer> yValueArray = new ArrayList<Integer>(cordsY.values());
int yTestValue = -1;
for (int i = 1; i < yValueArray.size() - 2; i++) {
if (yTestValue == -1) {
yTestValue = yValueArray.get(i);
continue;
}
if (yTestValue != yValueArray.get(i)) {
yIsValid = false;
break;
}
}
return (xIsValid && yIsValid);
}