HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Integer Partition

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
partitionintegerstackoverflow

Problem

The aim is to enumerate all possible sets of whole numbers whose sum is a given integer.

class partition
{
    public static void main(String[] ar)
    {
        part(66);
    }

    public static void part(int n)
    {
        part(n,1,"");
    }

    public static void part(int n, int st, String prefix)
    {
        if(n == 0)
        {
            System.out.println(prefix.substring(1));
            return;
        }
        for(int i = st; i <= n; i++)
            part(n-i,i,prefix + " " + i);
    }
}


Please help to improve my code and suggest a better solution.

Solution

My first observation is that your variable names mean nothing. n and st should describe what they are supposed to represent.

I don't like having the println in the part function. In my opinion, the value should be returned back up the stack and printed in the user interface layer. Please see Separation of Concerns for more information. This will allow your code to be followed a little easier.

Other than that, not too many other things to note.

Context

StackExchange Code Review Q#36722, answer score: 6

Revisions (0)

No revisions yet.