• Post Reply Bookmark Topic Watch Topic
  • New Topic

i cant find the logic in this recurtion  RSS feed

 
johny doe
Ranch Hand
Posts: 78
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how does it work??

Public static void partitions (int n)
{
partitions (n, n, "");
}
Public static void partitions (int n, int max, String prefix)
{
if(n==0)
{
System.out.println(prefix);
}
else
{
for(int i= Math.min(n,max); i>=1, i--)
{
partitions (n-i, i, prefix+" "+i);
}
}
}
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please use code tags, which make code easier to read. Please use ctrl-C and ctrl-V rather than writing code out; this will save you from little mistakes like "Public" for "public".

You have a base case, though I think maybe it would work better with 1 than with 0.

You have a reduction step.

You are calling your own method.

You will have to go through the whole method with a pencil and paper and work out what is happening. You will get something like this:
  • You go into the partition(int) method
  • This calls the partitions(int, int, String) method
  • You go into the partitions(int, int, String) method
  • It starts by seeing whether n is zero.
  • If it is zero it . . . .
  • etc etc.
  • As an alternative, see if you can get that method to run, get an IDE and debug it with the step into, step over, and step return commands. Do it several times and inspect the variables and the method call stack (which is usually displayed somewhere) and watch what happens. I told you how to do that about a week ago.
     
    Raghavan Muthu
    Ranch Hand
    Posts: 3389
    Mac MySQL Database Tomcat Server
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    As an easy alternative, you can easily put a meaningful System.out.println() as and when required, if debugging in an IDE mentioned by Campbell sounds too big for you.
     
    Campbell Ritchie
    Marshal
    Posts: 56536
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Originally posted by Raghavan Muthu:
    As an easy alternative . . .
    Good idea
     
    It is sorta covered in the JavaRanch Style Guide.
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!