java - Better way to return from recursive function when there are 2^n conditions -


suppose have n = 3 boolean variables -- a, b , c in java.

these variables can have total of 8 (2^n = 2^3) combinations.

these conditions used determine return statement in recursive function follows:

static int recursivefunc(int x){      boolean a, b, c;      = getboolval(x);     b = getboolval(x + 1);     c = getboolval(x + 2);      if(a == true && b == true && c == true)        //7         return recursivefunc(x + 1) + recursivefunc(x + 2) + recursivefunc(x + 3);      else if(a == true && b == true && c == false)  //6         return recursivefunc(x + 1) + recursivefunc(x + 2);      else if(a == true && b == false && c == true)  //5         return recursivefunc(x + 1) + recursivefunc(x + 3);      else if(a == true && b == false && c == false) //4         return recursivefunc(x + 1);      else if(a == false && b == true && c == true)  //3         return recursivefunc(x + 2) + recursivefunc(x + 3);      else if(a == false && b == true && c == false) //2         return recursivefunc(x + 2);      else if(a == false && b == false && c == true) //1         return recursivefunc(x + 3);      else                                           //0         return 0;  }  static boolean getboolval(int x){      if(some condition respect x)         return true;      else         return false;  } 

as can see, number of conditions pretty lengthy increasing value of n.

however, return statement can generated in n + 2 steps (instead of 2^n) follows:

string returnstat = "";  if(a == true)     returnstat += "recursivefunc(x + 1) + ";  if(b == true)     returnstat += "recursivefunc(x + 2) + ";  if(c == true)     returnstat += "recursivefunc(x + 3) + ";  if(returnstat == "")     returnstat = "0";  else     returnstat = returnstat.substring(0, returnstat.length() - 3); //removing " + " 

is there anyway in can return returnstat statement? perhaps, --

return stringtocode(returnstat); 

if not, how overcome situation?

recursivefunc returns int, add ints:

int result = 0;  if (a)     result += recursivefunc(x + 1); if (b)     result += recursivefunc(x + 2); if (c)     result += recursivefunc(x + 3);  return result; 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -