1

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, 1}  2. {1, 1, 2} 3. {1, 2, 2} 4. {2, 2, 2}
    

and when max = 3 and n = 2

  1. {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");
    }
}
zx485
  • 28,498
  • 28
  • 50
  • 59
Joe
  • 21
  • 2
  • 3
    Please edit the question to contain the relevant code. Don't post links. – Eran Jan 06 '19 at 09:32
  • i tried many times but I was not able to pastebin is not violation of the forums laws.. – Joe Jan 06 '19 at 09:35
  • What do you mean by "number of options possible for the array" ? – c0der Jan 06 '19 at 17:18
  • Possible duplicate of [Setting numbers from 1 to chosen number using recursion only](https://stackoverflow.com/questions/54064604/setting-numbers-from-1-to-chosen-number-using-recursion-only) – P. van der Laan Jan 06 '19 at 22:26
  • (duplicate) I answered the same question here: https://stackoverflow.com/questions/54064604/setting-numbers-from-1-to-chosen-number-using-recursion-only – P. van der Laan Jan 06 '19 at 22:27

1 Answers1

0

you have a problem with your code you first increment each cell until max value and then when you reach max you shift to the next cell of the array that's way for every example that max > 2 you want return values when both cells need to increment for example in the second test you miss {2,2}

your steps are :

  • {1,1}
  • {2,1}
  • {3,1}
  • {3,2}
  • {3,3}
Naor Tedgi
  • 5,204
  • 3
  • 21
  • 48