Click here to Skip to main content
13,146,014 members (44,995 online)
Rate this:
 
Please Sign up or sign in to vote.
See more:
Hi guys
i need to analyze this function:

a=5,2,6,3,9,1 ; sz=6 ; k=20
int f4(int *a, int sz, int k)
{
  if(sz>0 && k!=0){
    if(f4(a+1,sz-1,k-a[0]))
      return 1;
    else
      return f4(a+1,sz-1,k);
  }
  return (k ? 0 : 1);
}

but idk how to follow after all of the returns, pls explain it to me,THX.
Posted 11-Feb-13 1:05am
idobry431
Updated 11-Feb-13 2:12am
CPallini408.3K
v2
Comments
E.F. Nijboer 11-Feb-13 7:38am
   
The only return you need to follow is that of the if statement. Write them down in a tree like fashion so you keep track of how deep you are.
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

I'm not sure what's confusing you here, perhaps you just need to unpack the code a bit. If you want to know what it's trying to achieve you find that out by reading the documentation or asking the author, the code can only tell you want it does to its parameters not why anyone would want to do that.

The C++ version below should be easy enough to understand.
bool f4( int* array, int size, int k )
{
  if( size > 0 && k != 0 )            //if there is anything to process
  {
    if( f4( array + 1, size - 1, k - a[ 0 ] ) )  //if processing all the elements after the first one against a k of ( k - first element ) returns true then
    {
      return true;
    }
    else                                       //otherwise
    {
      return f4( array + 1, size - 1, k );     //return the result of processing all the elements after the first one against k itself
    }
  }
  return ( k ? false : true ); //In the no-more-to process case return the inverse of k, true if k is 0, false otherwise
}


What all this is to achieve I do not know but if you really badly want to find out you can do it yourself on paper by following the steps or just single step your debugger while watching the stack.
  Permalink  
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

That recursion works like all other recursions[^] do: you have to follow the code (with a debugger or, virtually, by inspection) to understand what happens.
  Permalink  

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy |
Web01 | 2.8.170915.1 | Last Updated 11 Feb 2013
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100