This discussion is archived
2 Replies Latest reply: Dec 29, 2012 11:46 AM by 870083 RSS

Dynamic Iteration

870083 Newbie
Currently Being Moderated
Hi everyone,

So I'm hoping I am posting this question in the correct section.
Below I have written a small code example of what I am trying to do:
public class IteratingCombinationsManual {
    
    public static void main(String[]args){
        int combinations = 0;
        for(int a = 1; a <= 3; a++){
            for(int b = 1; b <= 3; b++){
                for(int c = 1; c <= 3; c++){
                    System.out.println(c + "/" + b + "/" + a);
                    combinations++;
                }
            }
        }
        
        System.out.println("Combinations: " + combinations);
    }
}
So the output will be 3 columns of numbers iterating through every combination you can have with 3 colmuns of numbers ranging from 1 to 3. My question is that my actual problem is I don't know how many columns there will be as the user will determine this so I can't hard code the number of embeded loops to match the number of columns and I was wondering if there is any known design patterns or methods to solve a problem like this. I've been trying to rack my brains with this for awhile and I'm starting to think it will have to be some sort of OO solution as opposed to just the correct arrangement of loops.

Any guidance or suggestions would be greatly appriciated.

Thanks.
  • 1. Re: Dynamic Iteration
    TPD-Opitz-Consulting-com Expert
    Currently Being Moderated
    The keyword is <i>recursion</i>.

    Collect the numbers given by the user in a List.

    Call a method which takes the list a parameter.

    in that Method write out the first element of the List (with <tt>System.out.print()</tt> to avoid newline).

    if the list containes more than one element create a new List without the first element and call the method again with the new shorter list.

    If the list has only one element left write out a newline and return.

    bye
    TPD
  • 2. Re: Dynamic Iteration
    870083 Newbie
    Currently Being Moderated
    Thank you for the reply, I got a feeling recursion would be the answer but I can't say I always fully understand it. I think I see what you are getting at and I'm going to try and get my head around it and see how it goes.

    I''m going to try and create another small example before implementing it in my main code as the actual problem is more complicated than that but I get the feeling the principle will be the same.

    Thank you.

Legend

  • Correct Answers - 10 points
  • Helpful Answers - 5 points