Well, this can be done without recursion if you maintain an array, list, or something else that tells you where you are in each of the arrays.
Say we save a list of these items:
private static class Pair { private int currIndex = 0; int length; public Pair( int length ) { this.length = length; } public boolean updateAndCheckCarry() { currIndex ++; if ( currIndex >= length ) { currIndex = 0; return true; } return false; } public int getIndex() { return currIndex; } }
The idea is that we look at each array, say, the array {4, 5} . We will start with four, as we go through our cycle, we will update this to five. But then the element above changes, and we need to move on to four again. This class helps us with this.
So, we compile our list of indices:
public static LinkedList<Pair> prepareIndexList(List<int[]> listToIndex) { LinkedList<Pair> result = new LinkedList<>(); for ( int[] element : listToIndex ) { Pair item = new Pair(element.length); result.add(item); } return result; }
It's quite simple - we just look at our list and collect lengths to help us find out when each index needs to be reset.
At each iteration, we have to go through the list and print the numbers in the current index of each array. Therefore, if we have index 2 for the first array, 1 for the second and 0 for the last, we collect 4 , 5 and 1 from your example.
public static String getNextValue(List<int[]> valuesList, List<Pair> indexList) { StringBuilder sb = new StringBuilder(valuesList.size()); Iterator<Pair> indexIter = indexList.iterator(); for ( int[] element : valuesList ) { int index = indexIter.next().getIndex(); sb.append(element[index]); } return sb.toString(); }
Now the real "meat" of this solution is updating the indexes. This is very similar to adding 1 to the number. Imagine you have the number 1958 and you add 1 to it. He becomes 1959 . Now you add 1. again. So 9 becomes 0 , and you need to move 1 to 5. Now you have 1960 . Save it and you will get until 1999 . At this point, you add 1, zero 9, drag it to the left, then zero it and drag it to the left, then reset it and drag it to the left, and you end up in 2000 .
In the same way - starting from the right and going through the left when we need to carry 1 - we also update our list of indices:
public static boolean updateIndexList(LinkedList<Pair> indexList) { Iterator<Pair> iter = indexList.descendingIterator(); boolean hasCarry = true; while ( iter.hasNext() && hasCarry ) { hasCarry = iter.next().updateAndCheckCarry(); } return hasCarry; }
If we have a βcarryβ from the left-most index β an index that belongs to the head of our source list, this means that we have finished the program since we passed all the elements in the first array. When this happens, the above method returns true.
Now we only need to call our methods:
LinkedList indexList = prepareIndexList(list); boolean completed = false; while ( ! completed ) { System.out.println(getNextValue( list, indexList )); completed = updateIndexList(indexList); }