What are some efficient ways I can generate distinct halves of an integer array?

55 views Asked by At

Given an integer array, I want to print out all the distinct pairs of halves of the array. [2,1] [3,2] and [3,2] [2,1] can be considered distinct.

I'm sure there's a brute force way, but I want something more efficient and I can't really figure it out.

1

There are 1 answers

2
Reilas On

"... I'm sure there's a brute force way, but I want something more efficent and I can't really figure it out. ..."

You can encapsulate the ArrayList class, to provide a contains method.

Here is an example.

class IntArrayList extends ArrayList<Integer[]> {
    boolean contains(int a, int b) {
        for (Integer[] e : this)
            if ((e[0] == a && e[1] == b) || (e[0] == b && e[1] == a))
                return true;
        return false;
    }

    boolean add(int a, int b) {
        return super.add(new Integer[] { a, b });
    }
}
IntArrayList list = new IntArrayList();
Integer[] values = { 1, 2, 3 };
for (int a : values)
    for (int b : values) {
        if (a == b) continue;
        if (!list.contains(a, b)) list.add(a, b);
    }

Output

[1, 2]
[1, 3]
[2, 3]