This function is supposed to take in 2 parameters: n
the number of ints in an array and max
which is the max value of an int in the array (the default value is 1). This function returns the number of options possible for the array.
For example when n
= 3 and max
= 2
{1, 1, 1} 2. {1, 1, 2} 3. {1, 2, 2} 4. {2, 2, 2}
and when max
= 3 and n
= 2
{1, 1} 2. {1, 2} 3. {1, 3} 4. {2, 2} 5. {2, 3} 6. {3, 3}
This is my code:
public class Ex14 {
public static int howManySorted(int n, int max) {
int[] myIntArray = new int[n];
fillAnArray(myIntArray, 0);
return howManySorted(myIntArray, max, 0, 1);
}
private static int howManySorted(int[] myIntArray, int max, int i, int way) {
way++;
myIntArray[i]++;
if (i < myIntArray.length - 1)
if (myIntArray[i] == max)
i++;
if (myIntArray[myIntArray.length - 1] == max) return way;
return (howManySorted(myIntArray, max, i, way));
}
//filling the array with ones for defualt way when all values equals 1
private static void fillAnArray(int[] myIntArray, int t) {
if (t == myIntArray.length)
return;
else
myIntArray[t] = 1;
fillAnArray(myIntArray, t + 1);
}
}
My code seems to give me the correct value 4 if using the first example on the second it skips one array. tester:
public class Tester14 {
public static void main() {
System.out.println("Test: Checking method 'howManySorted' on n=3 and max=2");
System.out.println("Expected result = 4, Student result = "
+ Ex14.howManySorted(2, 3) + "\n");
}
}