Thursday, November 20, 2008

Unique combinations for a given number in c programming language

Unique combinations for a given number

How do I write a program which can generate all possible combinations of numbers from 1 to one less than the given number ?

main( )
{
long steps, fval, bstp, cnt1 ;
int num, unit, box[2][13], cnt2, cnt3, cnt4 ;
printf ( "Enter Number " ) ;
scanf ( "%d", &num ) ;
num = num <> 12 ? 12 : num ;
for ( steps = 1, cnt1 = 2 ; cnt1 <= num ; steps *= cnt1++ ) ;
for ( cnt1 = 1 ; cnt1 <= steps ; cnt1++ )
{
for ( cnt2 = 1 ; cnt2 <= num ; cnt2++ )
box[0][cnt2] = cnt2 ;
for ( fval = steps, bstp = cnt1, cnt2 = 1 ; cnt2 <= num ; cnt2++ )
{
if ( bstp == 0 )
{
cnt4=num ;
while ( box[0][cnt4] == 0 )
cnt4-- ;
}
else
{
fval /= num - cnt2 + 1 ;
unit = ( bstp + fval - 1 ) / fval ;
bstp %= fval ;
for ( cnt4 = 0, cnt3 = 1 ; cnt3 <= unit ; cnt3++ )
while ( box[0][++cnt4] == 0 ) ;
}
box[1][cnt2] = box[0][cnt4] ;
box[0][cnt4] = 0 ;
}
printf ( "\nSeq.No.%ld:", cnt1 ) ;
for ( cnt2 = 1 ; cnt2 <= num ; cnt2++ )
printf ( " %d", box[1][cnt2] ) ;
}
}

This program computes the total number of steps. But instead of entering into the loop of the first and last combination to be generated it uses a loop of 1 to number of combinations. For example, in case of input being 5 the number of possible combinations would be factorial 5, i.e. 120. The program suffers from the limitation that it cannot generate combinations for input beyond 12 since a long int cannot handle the resulting combinations.

No comments:

Blog List