Forums Register Login

i cant find the logic in this recurtion

+Pie Number of slices to send: Send
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);
}
}
}
+Pie Number of slices to send: Send
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.
    +Pie Number of slices to send: Send
    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.
    +Pie Number of slices to send: Send
     

    Originally posted by Raghavan Muthu:
    As an easy alternative . . .

    Good idea
    Not looking good. I think this might be the end. Wait! Is that a tiny ad?
    a bit of art, as a gift, the permaculture playing cards
    https://gardener-gift.com


    reply
    reply
    This thread has been viewed 670 times.
    Similar Threads
    help in solving recursive problems??
    i want to try and solve this question..
    i want to try and solve this question..
    Integer Partition using recursion
    Have problem in understanding the logic of Integer Partition
    Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
    More...

    All times above are in ranch (not your local) time.
    The current ranch time is
    Apr 16, 2024 05:15:21.