222 Intermediate C Programming
-: 75: }
-: 76: }
101392: 77: return 1;
-: 78:}
-: 79:
107374 1824: 80: void partitio n2 ( in t * arr , i n t ind , in t left )
-: 81:{
-: 82: i nt val ;
107374 1824: 83: i f ( left == 0)
-: 84: {
5368709 1 2: 85: i f ( isValid ( arr , ind ) == 1)
-: 86: {
101393: 87: prin t Partit ion ( arr , ind );
-: 88: }
161061 2736: 89: return ;
-: 90: }
161061 2735: 91: for ( val = 1; val <= left ; val ++)
-: 92: {
107374 1823: 93: arr [ ind ] = val ;
107374 1823: 94: partition2 ( arr , ind + 1 , left - val );
-: 95: }
-: 96:}
-: 97:
1: 98: in t main ( i n t argc , char * argv [])
-: 99:{
1: 100: i f ( argc != 2)
-: 101: {
#####: 102: return EXIT_FAI LURE ;
-: 103: }
1: 104: i nt n = ( in t ) strtol ( argv [1] , NULL , 10) ;
1: 105: i f ( n <= 0)
-: 106: {
#####: 107: return EXIT_FAI LURE ;
-: 108: }
-: 109: in t * arr ;
1: 110: arr = malloc ( s i z e o f ( i n t ) * n) ;
1: 111: printf ( " ---- - Partition 1- -- --\ n" );
1: 112: p a rtition1 ( arr , 0 , n ) ;
1: 113: printf ( " ---- - Partition 2- -- --\ n" );
1: 114: p a rtition2 ( arr , 0 , n ) ;
1: 115: free ( arr );
1: 116: return EX IT_SUCCE SS ;
-: 117:}
Please pay special attention to lines 85 and 87. Line 85 says isValid is called 536870912
times but it is true only 101393 times. In other words, most generated partitions are invalid.
This is another way to obtain the same information: partition2 generates many invalid
partitions.