I have been trying to understand the next recursion, the code ain't mine, it is a code to calculate the partition theory of n numbers, but the recursion of it, it's making me confused. Can anybody explain me how does it work in order I can finally understand it. Thanks.
package practicingjava;
import java.util.Scanner;
/**
* @author JVASQUEZ
*/
public class PracticingJava {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
partition(n, n, "");
}
public static void partition(int max, int n, String prefix) {
if (n == 0) {
System.out.println(prefix);
}
for (int i = Math.min(max, n); i >= 1; i--) {
partition(i, n - i, prefix + " " + i);
}
}
}
For a more basic primer on recursion in java : http://www.javatpoint.com/recursion-in-java
But in thie case, partition is called once and then continues to call itself until n reaches zero. That is what the previous if statement was doing. If that if statement wasn't there it would continue on infinitum. The loop then pulls variables from the arguments and therefore the previously run method. It breaks the problem down into smaller pieces that way.