Aki K
Aki K

Reputation: 1262

Equally split array in 3 parts

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.

Upvotes: 0

Views: 4431

Answers (2)

dnyan waychal
dnyan waychal

Reputation: 433

Try this

        int len= data.Length;
        int pos = len / 3;
        int remaining = len % 3;

        int firstpos = pos + (remaining > 0 ? 1 : 0);
        int centerpos=pos;
        int lastpos = pos + (remaining / 2);

Upvotes: 0

Jean Logeart
Jean Logeart

Reputation: 53839

You can simply write:

int elements = data.length;
int mod = elements % 3;
int div = elements / 3;

int sizeLeft = div + (mod > 0 ? 1 : 0);
int sizeCenter = div;
int sizeRight = div + (mod > 1 ? 1 : 0);

Upvotes: 2

Related Questions