Writing a recursion algorithm to get anagrams of a string.
Expected output for string abc
is ['abc', 'acb', 'bac', 'bca', 'cab', 'cba']
However, what I get is [ 'abc', 'acb', 'ba', 'cab', 'cba' ]
.
I know where the issue is: When the recursion goes back to level 0 (meaning str==='abc' and i==1), substring works (exracts 'a'), but slice does not(does not extract c).
function anagramPermutationMemo(str, memo, resultsArr, level) {
if (!memo) {
memo = '';
resultsArr = [];
level = 0;
}
console.log('str -', str);
console.log('memo -', memo, '\n');
if (str.length === 0) {
resultsArr.push(memo);
return;
}
for (var i in str) {
console.log('level', level);
console.log('str', str);
console.log('i -', i, str[i]);
console.log('substring', str.substring(0, i));
console.log('slice', str.slice(i + 1));
var newStr = str.substring(0, i).concat(str.slice(i + 1));
console.log('newStr - ', newStr, '\n');
anagramPermutationMemo(newStr, memo + str[i], resultsArr, level + 1);
}
level -= 1;
console.log('backtrack', level,'\n');
return resultsArr;
};