View Single Post
Old Jan 17th, 2006, 10:36 AM   #10
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, this isn't an easy problem, so don't get discouraged

Take it one step at a time. You have two arrays, a and b each of size n. You want to create every possible combination of the two. So let's walk through what you need to do to create a single combination.

You start off with a[0], and you have n possibilities. You can have a[0]b[0], a[0], a[0]b[1] all the way up to a[0]b[n].

For a[1] you can use any number except for the one you used for a[0]. So you have n-1 possibilities. At a[2] you have n-2 possibilities, at a[3] you have n-3 possibilities and so on.

This continues until you are at a[n - 1], the last element of a. You're also at the last element of b, so there's only one possibility left to you. At this point, you have all the elements in the sequence, which you can print to the screen.

So your limiting condition is when a and b have only one element each. And at this point, you can print out your sequence.

With recursion, you can pass data one of two ways. You can pass it from the bottom of the recursion to the top via a return value. Or you can pass it from the top to the bottom via a parameter. Because we want to print out the sequence at the bottom of the recursion stack, we need to use an extra parameter to pass data down:

void group(List<String> a, List<Integer>b, List<String>output)
{
    if (a.size() != b.size())
    {
        throw new Exception("a and b must be the same length");
    }

    if (a.size() == 1)
    {
        output.add(a.get(0) + " = " + b.get(0))

        for (item : output)
        {
            println(item);
        }
    }
    else
    {
        // When arrays have more than one element...
        // ...Some recursion code is needed here.
    }
}
I should also mention that using a List would be a good idea, since a List object is of variable size, so you can add and remove elements. A plain array is of fixed size, so you have to create a new array everytime you want to reduce or increase it's size. Not too convenient!

You can use Arrays.asList to convert an array into a list:
import java.util.Arrays;
...

List<String> list = Arrays.asList(stringArray);

Last edited by Arevos; Jan 17th, 2006 at 10:47 AM.
Arevos is offline   Reply With Quote