I have an array and I want to split it almost equally in 3 parts. I know how to do that but I also want to handle the case of having 2 elements in my array.
In that case I want the center array to be an empty array of zero elements (center.length == 0) (must have zero elements not just a null array).
Here is what I did:
int elements = data.length;
int sizeLeft;
int sizeCenter;
int sizeRight;
if (elements > 2) {
if (elements % 3 == 0) {
sizeLeft = elements / 3;
sizeCenter = elements / 3;
sizeRight = elements / 3;
} else if (elements % 3 == 1) {
sizeLeft = (elements / 3) + 1;
sizeCenter = elements / 3;
sizeRight = elements / 3;
} else { //if (elements % 3 == 2)
sizeLeft = (elements / 3) + 1;
sizeCenter = elements / 3;
sizeRight = (elements / 3) + 1;
}
int[] left = makeArray(data, 0, sizeLeft);
int[] center = makeArray(data, sizeLeft, sizeCenter);
int[] right = makeArray(data, sizeLeft + sizeCenter, sizeRight);
} else if (elements == 2) {
int[] center = new int[]{};
int[] left = makeArray(data, 0, 1);
int[] right = makeArray(data, 1, 1);
}
The makeArray method:
public static int[] makeArray(int[] data, int startCopy, int size) {
int[] array = new int[size];
System.arraycopy(data, startCopy, array, 0, size);
return array;
}
data is the main array that is going to be split in 3 parts: left center and right.
What I want to ask is if there a way to combine the two ifs in one if nicely and elegantly.
Thank you.
You can simply write: