My C++ recursion function is not calling itself or doing anything after it enters the first if statement (if (perm.empty()). I was confused so I converted the same logic to python and it works just fine. Am I missing something? Thank you all
C++ code:
bool permMaker(vector<int> choices, vector<int> & perm, int n, int i ){
// remove last added element from chocies
if (!perm.empty()) {
choices.erase(remove(all(choices), perm.back()), perm.end());
cout << "in" << endl;
}
if (perm.size() == n) {
return true;
}
rap(num, choices){
if (perm.empty()) {
perm.push_back(num);
bool ans = permMaker(choices, perm, n, i +1 );
if (ans) {
return true;
}
perm.pop_back();
}
else {
if (abs(num - perm.back()) > 1) {
perm.push_back(num);
bool ans = permMaker(choices, perm, n, i + 1);
if (ans) {
return true;
}
perm.pop_back();
}
}
}
return false;
}
Here is the same logic in python which is working
def permMaker(choices, perm, length):
choices = choices[:]
if len(perm) >0:
choices.remove(perm[-1])
if len(perm) == length:
return True
for num in choices:
if len(perm) == 0:
perm.append(num)
ans = permMaker(choices, perm, length)
if ans:
return True
perm.pop()
else:
if abs(num - perm[-1]) > 1:
perm.append(num)
ans = permMaker(choices, perm, length)
if ans:
return True
perm.pop()
return False