Exercise 71 SmartCombining

153 views
Skip to first unread message

wolf...@gmail.com

unread,
Apr 6, 2014, 4:41:16 AM4/6/14
to moo...@googlegroups.com
Hi and hope someone can help. My method seems to work but when I submit it it fails in some respects. When I check it with the values that it says it fails on, it works so I'm not sure what's going on.

Thanks for your interest.

Here's my code

    public static void smartCombine(ArrayList<Integer> list1, ArrayList<Integer> list2) {
        ArrayList<Integer> tempList = new ArrayList<Integer>();
        tempList.addAll(list2); // Copies list2 values into tempList
        // Next line is mainly for checking errors before anything is done
        System.out.println("List1: " + list1 + "\tList2: " + list2 + "\ttempList: " + tempList);
        for (int i : list2) {
            System.out.println("i: " + i);
            if (list1.contains(i)) {
                tempList.remove(i); // Removes an element from tempList if it already exists in list1
            }
        }
        list1.addAll(tempList); // Copies the non duplicated values from tempList into list1
    }

It tells me it fails with the following but when I hard code these values into the main method it works just fine:-
Combination of lists [10, 11] and [5] should contain the number 5.
Combination of lists [5, 1, 2] and [40] should contain the number 40.
Combination of lists [10, 11, 12, 13] and [5, 6, 7, 8, 9] should contain the number 5.

wolf...@gmail.com

unread,
Apr 6, 2014, 4:52:59 AM4/6/14
to moo...@googlegroups.com, wolf...@gmail.com

Now solved, well sort of solved but I still don't understand why the tester failed my original version. FYI I solved it by:-
  1. Not using a tempList ArrayList
  2. Using a direct comparison between list2 elements and list1, and if the value doesn't exist in list 1, then add it otherwise move onto the next list2 element.
Thanks again for your interest but if anyone can tell me why it failed when it appeared to work just fine, I'd be interested.
Reply all
Reply to author
Forward
0 new messages