Giffary Giffary - 4 months ago 29
Java Question

How to union, intersect, difference and reverse data in java

I have some problem, i want to union, intersect, difference and reverse operator in java.

first i have 2 arraylist

a = [0,2,4,5,6,8,10]
b = [5,6,7,8,9,10]


a union b is return
c = [0,2,3,4,5,6,7,8,9,10]


a intersect b is return
c = [5,8,10]


a defference b is return
c = [0,2,3,4]


reverse
a = [10,8,6,5,4,2,0]


something like this.

how to implement that method in java?




Update: I have to start with this template:

package IntSet;
import java.util.ArrayList;
import java.util.Collection;


public class IntSet {

private ArrayList<Integer> intset;

public IntSet(){
intset = new ArrayList<Integer>();
}

public void insert(int x){
intset.add(x);
}

public void remove(int x){
//implement here
intset.indexOf(x);
}

public boolean member(int x){
//implement here
return true;
}

public IntSet intersect(IntSet a){
//implement here
return a;
}

public IntSet union(IntSet a){
//implement here
return a;
}

public IntSet difference(IntSet a){
//implement here
IntSet b = new IntSet();
return b;
}

Answer
//Union 
List<Integer> c = new ArrayList<Integer>(a.size() + b.size());
addNoDups(c,a);
addNoDups(c,b);

private void addNoDups(List<Integer> toAddTo,List<Integer> iterateOver) {
    for(Integer num:iterateOver){
        if(toAddTo.indexOf(num) == -1) {
            toAddTo.add(num);
        }
    }
}

//intersection
List<Integer> c = new ArrayList<Integer> (a.size() > b.size() ?a.size():b.size());
c.addAll(a);
c.retainAll(b);

//difference a-b
List<Integer> c = new ArrayList<Integer> (a.size());
c.addAll(a);
c.removeAll(b);
Comments