I have this function:
public void func1(int d, double delta, double min, double max )
{
if( d == 1 )
{
for( double i=min ; i <= max ; i++ )
System.out.println(i);
}
if(d == 2 )
{
for( double i=min ; i <= max ; i++ )
for( int j = min ; j <= max ; j++ )
System.out.println(i, j);
}
if(d == 3 )
{
for( double i=min ; i <= max ; i++ )
for( int j = min ; j <= max ; j++ )
for( int k=min ; k <= max ; k++ )
System.out.println(i, j, k );
}
}
How to make it dynamic? I.e.,: how to not use the if
statement so that the function can work with any given d
?
Currently, if I want the function to work with d=5, then I have to write five nested for loops and add an if
statement.
Feels like a homework question but I'll bite.
My answer works like an odometer on a car. You have wheels of digits. When each wheel gets to 9, the next one gets bumped up a slot and the current one return to 0. It uses no recursion and maintain the full array of numbers at all time. Instead of
println
, you can add the array to a list of array to capture all permutations. (The last time I touched Java was in 2004 so pardon me if this doesn't look "modern")There are a couple assumptions that I've made:
min < max
delta
steps perfectly frommin
tomax
. For example,delta = 1, min = 1, max = 10
. I haven't tested cases likedelta = 2, min = 1, max = 2
.