views:

268

answers:

1

Similar to this: http://stackoverflow.com/questions/426878/is-there-any-way-to-do-n-level-nested-loops-in-java

I want to create a recursive function, which generates N nested loops, where the indicies depend on the depth of the loop. So basically, I want to do this recursively:

// N = 3, so we want three nested loops

for(int i1 = 0; i1 < max; i1++){
    for(int i2 = i1+1; i2 < max; i2++){
        for(int i3 = i2+1; i3 < max; i3++){
            int value1 = getValue(i1);
            int value2 = getValue(i2);
            int value3 = getValue(i3);
            doSomethingWithTheValues( ... );
        }
    }
}

I've looked at the answers in the other question, and tried to modify the answer (by oel.neely), but without luck. My guess is that it only needs a small modification, but right now, I'm just confusing myself!

+2  A: 

Its C#, but should be easily convertable to Java:

class ImmutableStack<T>
{
    public readonly T Head;
    public readonly ImmutableStack<T> Tail;

    public ImmutableStack(T head, ImmutableStack<T> tail)
    {
        this.Head = head;
        this.Tail = tail;
    }

    public static ImmutableStack<T> Cons(T head, ImmutableStack<T> tail)
    {
        return new ImmutableStack<T>(head, tail);
    }

    public static ImmutableStack<T> Reverse(ImmutableStack<T> s)
    {
        ImmutableStack<T> res = null;
        while (s != null)
        {
            res = Cons(s.Head, res);
            s = s.Tail;
        }
        return res;
    }
}

class Program
{
    static void AwesomeRecursion(int toDepth, int start, int max, ImmutableStack<int> indices)
    {
        if (toDepth < 0)
        {
            throw new ArgumentException("toDepth should be >= 0");
        }
        else if (toDepth == 0)
        {
            Console.Write("indices: ");
            indices = ImmutableStack<int>.Reverse(indices);
            while (indices != null)
            {
                Console.Write("{0}, ", indices.Head);
                indices = indices.Tail;
            }
            Console.WriteLine();
        }
        else
        {
            for (int i = start; i < max; i++)
            {
                AwesomeRecursion(toDepth - 1, i + 1, max, ImmutableStack<int>.Cons(i, indices));
            }
        }
    }


    static void Main(string[] args)
    {
        AwesomeRecursion(4, 1, 10, null);
        Console.WriteLine("Done");
        Console.ReadKey(true);
    }
}

We keep the indices on an immutable stack since it makes backtracking so much easier than mutable stacks or queues.

Juliet
This works! Thanks. I could not, however, get the generics to work in a static content in java. But it might be a java thing, I didn't bother debugging it much.
Frederik Wordenskjold