I'm trying to generate all capital permutations of a string.
For example:
capitalPermutations(word) - Given a string of letters, return all the possible combinations of lower and uppercase letters of that word.
Example: 'abc'
Ouput: ['abc' 'Abc' 'aBc' 'ABc' 'abC' 'AbC' 'aBC' 'ABC']
Implement this in both iterative and recursive way.
This is my attempt:
function capitalPermutations(word) {
const res = new Set();
// Push the actual word first.
res.add(word);
helper(word, res, '');
return res;
function helper(word, res, str='') {
if(str.length === word.length) return;
const len = word.length;
res.add(word);
// Capitalization
for(let i=0; i< word.length; i++) {
const substr = word.substring(0, i+1); // a, ab, abc
str += substr; // str === "ABC" | len = 3
const upper = str.toUpperCase(); // A, AB, ABC
const remaining = `${upper}${word.substring(i, len)}`; // Abc , ABc,
helper(remaining, res, str);
}
}
}
var testWord1 = "abc"
console.log(capitalPermutations(testWord1))
Issue: It's going into infinite recursion. Even though I have a breaking condition. Would really appreciate if someone can correct where I'm going wrong.
str += substr? In your base case, did you mean to compare to the originalwords length (the one passed tocapitalPermutations), or to thewordthat's getting passed in the recursive call? And why do you add thewordto theresult in each recursion step, not only once at the end?strto just keep track of how many strings I'm processing. I understand my code is confusing (just trying to learn!) appreciate your help and all your comments. In my base case, I was hoping to compare to my original word length (not the one that's getting passed) my bad!cab,bac, etc.? Isn't this assignment only about generating all the different variations of casing?