Thread: Recursive partition function

  1. #1
    Registered User
    Join Date
    Dec 2005
    Posts
    1

    Recursive partition function

    Hi,
    I have to write a recursive function that prints all the partitions for a given integer number,for example, the patitions of 4 are:
    4
    3 1
    2 2
    2 1 1
    1 1 1 1

    I created a function but there is a little problem that I can not realize. The output that I receive is:
    4
    3 1
    2 2
    1 1 <-- !!!!!!!
    1 1 1 1
    It seem like it misses a part of calculation.
    Can somebody help me find the problem in my function or suggest me altrnative one.
    My function:
    Code:
    void Partition(int n, int limit, int value[Npartition])
    {
    	int i, k=1, min;
    
    	if (n < limit)
    		min = n;
    	else
    		min = limit;
    	if (n>0)
    	{
    		for (i=min; i>0; i--)
    		{
    			for (k=0; k<Npartition; k++)
    			{
    				if (value[k] == 0)
    				{
    					value[k] = i;
    					break;
    				}
    			}
    
    			Partition(n-i, i, value);
    		}
    	}
    	else
    	{
    		for (i=0; i<Npartition; i++)
    			if (value[i] != 0)
                                                                    printf("%2d", value[i]);
    		printf("\n");
    		for (i=0; i<Npartition; i++)
    			value[i] = 0;
    	}
    }
    Initial function call is Partition(N, N, ValueArray)

    Thank you.

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > for (i=0; i<Npartition; i++)
    > value[i] = 0;
    To print
    2 2
    2 1 1
    I guess you shouldn't start at 0 when clearing your array for storing the result of the next calculation.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Recursive function
    By Fork in forum C Programming
    Replies: 3
    Last Post: 10-26-2006, 11:27 AM
  2. Replies: 28
    Last Post: 07-16-2006, 11:35 PM
  3. Calling a Thread with a Function Pointer.
    By ScrollMaster in forum Windows Programming
    Replies: 6
    Last Post: 06-10-2006, 08:56 AM
  4. c++ linking problem for x11
    By kron in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2004, 10:18 AM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM