简体   繁体   中英

What kind of helper method would I need to find an intersection between two arraylists?! (recursion only)

So I have the method

public ArrayList<String> intersection( ArrayList<String> A1, ArrayList<String> A2)

and Im not sure what my helper method would look like to return an ArrayList with elements that are in both A1 and A2, * in the order they occur in A1 *, and * leave A1 and A2 unchanged *

This is what I have written in main to test.

ArrayList A1 = new ArrayList();
ArrayList A2 = new ArrayList();
A1.add("a"); A1.add("b"); A1.add("c");
A2.add("b"); A2.add("c"); A2.add("d"); A2.add("e");
ArrayList intersect = Practice.intersection(A1,A2);
System.out.println(A1 + " intersect " + A2 + " = " + intersect);    

example output I want is [a, b, c] intersect [b, c, d, e] = [b, c]

If I understand you correctly, you want a recursive implementation for your intersection method. Basically, you want to iterate over a1 and check for each element, whether it is contained in a2 .

You can iterate over a1 using recursion: In each step, you remove the head of the list and check whether it is contained in a2 , and then you addAll elements from the intersection of the tail with a2 .

Look at the code: it should be mostly self-explanatory.

public static void main(String[] args) {
    ArrayList<String> a1 = new ArrayList<String>();
    ArrayList<String> a2 = new ArrayList<String>();
    a1.add("a"); a1.add("b"); a1.add("c");
    a2.add("b"); a2.add("c"); a2.add("d"); a2.add("e");
    ArrayList<String> intersect = intersection(a1, a2);
    System.out.println(a1 + " intersect " + a2 + " = " + intersect);
}

static <A> ArrayList<A> intersection(ArrayList<A> a1, ArrayList<A> a2){
    if(a1.isEmpty())
        return a1;
    else {
        ArrayList<A> result = new ArrayList<A>();
        A head = a1.get(0);
        if (a2.contains(head)) 
            result.add(head);
        ArrayList<A> tail = new ArrayList<>();
        tail.addAll(a1.subList(1, a1.size()));
        result.addAll(intersection(tail, a2));
        return result;
    }
}

There is a small pitfall with Java's mutable lists: Note that you could get head and tail with one simple operation: a1.remove(0) . However, if you do not make a defensive copy first, then you will modify your original a1 , which is definitively not what you want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM