View Single Post
Old Jan 17th, 2006, 4:05 PM   #14
Arevos
Programming Guru
 
Arevos's Avatar
 
Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 5 Arevos is on a distinguished road
Well, look at it this way: you're taking the lists a and b and combining them to produce the output list. So you're moving elements from your input lists to your output. As your output grows, your input shrinks.

But this isn't a serial process. You don't want to create one output list, you want to create many of them, one for each possible combination of the input lists a and b.

Let's take an example of how one, individual combination might be constructed. Let's say you have a and b defined so:
a = {"A", "B", "C"}
b = {1, 2, 3}
We begin with the first element, a[0]. It's pretty easy to see that there are three combinations for your output lists:
a[0]b[0]
a[0]b[1]
a[0]b[2]
So far so good? Lets say we go with a[0]b[1]. We will output this as "A = 2", because a[0] is "A" and b[1] is 2.

Now for the second element in our combination. We've used up A and 2, so we need to remove them from the lists, because we can only use each letter once in a combination. The sequence "A = 1, A = 2, B = 3", is, I assume, not a valid sequence because A appears twice.

So with A and 2 removed from our lists:
a = {"B", "C"}
b = {1, 3}
Here we repeat the step of combining a[0] with an element from b, but this time, a[0] is "B", and there are only 2 elements from b.

Let's say we go with a[0]b[0], or "B = 1". Again, we remove "B" and 1 from our lists, and we get:
a = {"C"}
b = {3}
Now we're at our limiting condition, because there's only one choice, a[0]b[0], or "C = 3". Since we're at our limiting condition, we can now print out our combination:
A = 2
B = 1
C = 3
That's one combination done. Let's return to the first step, and examine it a little more closely. Remember that when we started, we had three choices for the first element:
a[0]b[0]
a[0]b[1]
a[0]b[2]
We had three choices because the size of our lists, n was equal to three. This could quite easily have been 4, 5 or even 50:
a[0]b[0]
a[0]b[1]
...
a[0]b[n - 1]
A combination sequence could start with any one of these. So we need a loop that combines a[0] with each b, and then to pass this onto the next recursive method call.

Some helpful commands you'll probably need:
a.get(0);               // get the first element of a
a.get(j);               // get the (j-1)th element of a
List newA = new LinkedList(a); // make a copy of list a
a.add(newElement);             // add newElement onto the end of list a
String e = a.remove(j);      // remove the (j-1)th element of a and put it in e
Arevos is offline   Reply With Quote