I found a question online: Given input size print all well formed numbers of that size.
Example: size = 3
Numbers: 123, 234, 125 etc. Condition, say number is abc then a < b < c
I am trying to write a recursive code for this and since I suck at recursion am not able to figure out the base case, or how to come out of the recursion. I had one idea:
- I start from with lowest well formed number of the given size (just fill array with
for loop). Say size = 3, I start with123. Then I go on tillarr[0] == (10 - size))cause that is the max value ofarr[0]for the given size to be a well formed number.
My function would be printNumbers(int arr[], int size)
But am not sure if this would work. Need some pointers on the right direction.
public void findNumbers(int arr[], int size, int pos)
{
if(arr[0] == (10 - size))
return;
if(arr[pos] == (10 - size + pos))
{
pos--;
findNumbers(arr,size,pos);
}
System.out.println(Arrays.toString(arr));
arr[pos] = arr[pos] + 1;
findNumbers(arr,size,pos);
}
public static void main(String[] args)
{
int size = 3;
int pos = size-1;
int arr[] = new int[size];
for(int i = 0; i<size; i++)
{
arr[i] = i+1;
}
//System.out.println(Arrays.toString(arr));
WellFormed obj = new WellFormed();
obj.findNumbers(arr, size, pos);
}
This works fine: