I find this code rather odd. I think there are a number of problems you can work out, which I'll outline below.
Functions
You put the recursive version into a function called perm()
which is a good idea. I would do the same thing with the iterative version. This way your main()
function becomes more clear. I'd rename the recursive one to recursive_perm()
and make the new one iterative_perm()
. Then your main()
becomes:
int main(){
bool x = false;
bool y = false;
if(recursive_perm(x,y) == true){
puts("DONE\n");
}
puts("\n\n");
x = false;
y = false;
if(iterative_perm(x,y) == true) {
puts("DONE\n");
}
puts("NOTHING");
return 0;
}
Now you don't need the comments saying "RECURSIVE SOLUTION" and "ITERATIVE SOLUTION" because it's obvious from the names.
Fix Your Recursion
You recursive version doesn't do the same thing as your iterative version. In fact, it does a lot of really weird things. Why are you copying the input variables into const
members only to print them out? printf()
takes its arguments by value, so printing them won't change their values locally.
Also, why are you printing logical XOR when you're performing logical AND? The ^
operator is XOR in C-based languages. Your print statement tells the user that the value of x exclusive-or-ed with y is equal to the value of x logically anded with y.
Next, why are you calling perm(y+1,x);
before the return
statement? You don't do anything with its return value, so none of the work it does is at all useful. You throw out the results (though it does have the side effect of printing out some stuff).
What do these incorrect lines accomplish?
if(x == true){ return x;}
if(y == true){ return y;}
They appear to check if only 1 of the values is true and then return true, ignoring the other parameter. Therefore it is not actually calculating the permutations that you want it to calculate.
Doing addition on bool
values is not easy to read. I would not recommend doing that in the future. You can easily flip a boolean value from true
to false
by prepending it with the !
operator. Either that or change the function to take int
instead of bool
as you've done with the iterative version.
Testing bool
In general, it's considered better form to directly test a bool
variable in an if
statement rather than comparing it to true
or false
by doing this:
bool x = true;
bool y = false;
if (x) {
// x was true, do something here
}
if (!y) {
// y was false, do something here
}
What Does the Return Value Represent?
What does the return value of your perm()
function represent? If all you want to do is iterate through all possible permutations, it's not clear to me that it needs to return a value. Reading this, I would assume that if it's functioning correctly, it iterated all the values, otherwise it wouldn't have returned yet. If you want to know which combination returned true, you should probably return a struct
containing 2 values showing the final combination.