recursion - Getting help recursive C programming -
given array of length n
, , requirement write program calculate number of sub-sequences of length m
of given array.
below code it. please, have look.
int reccountsubseq(int seqlength, int length, int s[]) { int answer; if (seqlength == 0) { /* base case: found subseq of correct length */ return 1; } if (seqlength >= length) { /* base case: possible seqlength == length*/ return (seqlength==length); } /* recursive case: 2 branches */ answer = reccountsubseq(seqlength-1, length-1, s); /* s[length-1] in subseq*/ printf("answer=%d\n", answer); answer += reccountsubseq(seqlength, length-1, s); /* s[length-1] not in subseq */ printf("increased answer %d\n", answer); return answer; } void countsubseq(int seqlength, int length, int s[]) { printf("#subseq = %d\n", reccountsubseq(seqlength, length, s)); } int main() { int length; scanf("%d", &length); int seqlength; int i; int s[100]; (i=0;i<length; i++) { scanf("%d", &s[i]); } countsubseq(seqlength, length, s); return 0; }
now, my question: why value of seqlength
decreasing each time, , how code working ?
the function has undefined behaviour because @ least variable seqlength
not initialized:
int seqlength;
and task not clear. if have array n
elements number of continious subsequencies of length m
m <= n
equal n - m + 1
.
so writing such function not make great sense.:) not see in function there access array passed third argument.:)
insetad can suggest following function. @ least has sense.:)
#include <stdio.h> size_t reccountsubseq( const int a[], size_t n, size_t m ) { if ( m <= n ) { ( size_t = 0; < m; i++ ) printf( "%d ", a[i] ); printf( "\n" ); } return n <= m ? n == m : 1 + reccountsubseq( ++a, --n, m ); } int main( void ) { int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; printf( "there %zu subsequencies\n", reccountsubseq( a, sizeof( ) / sizeof( *a ), 3 ) ); return 0; }
its output is
1 2 3 2 3 4 3 4 5 4 5 6 5 6 7 6 7 8 7 8 9 there 7 subsequencies
i think incorrectly interpretating assignment , solution. should check descriptions anew.
Comments
Post a Comment