I have a word "ab", and I want to print all possible cases of those letters:
"aa"
"ab"
"ba"
"bb"
There is a function to do this:
function generateAnagrams(word, number) {
if (word.length < 2) {
return [word];
} else {
// By declaring all variables outside of the loop,
// we improve efficiency, avoiding the needless
// declarations each time.
var anagrams = [];
var before, focus, after;
var shortWord, subAnagrams, newEntry;
for (var i = 0; i < word.length; i++) {
before = word.slice(0, i);
focus = word[i];
after = word.slice(i + 1, word.length + 1);
shortWord = before + after;
subAnagrams = generateAnagrams(shortWord, number);
for (var j = 0; j < subAnagrams.length; j++) {
newEntry = focus + subAnagrams[j];
newEntry = newEntry.substr(0, number);
anagrams.push(newEntry);
}
}
//Remove all duplicate letters from array
//This prevent substr above from generate
anagrams = unique(anagrams);
return anagrams;
}
}
function unique(list) {
var result = [];
$.each(list, function (i, e) {
if ($.inArray(e, result) == -1) result.push(e);
});
return result;
}
//"ab" is inputed word
//2 is number of characters for each case
generateAnagrams("ab", 2);
From example code above, it give me a result of only two cases "ab" and "ba". Thus I want your help to modify the code to get the result that I want above.
JSFiddle: http://jsfiddle.net/LfL6sea3/
Extra explanation: For the suggestion of @Dekel, I think it is not really answer my question. My question is to get all possible case of the letters from a word. Look at an example below:
If I have a word "ab" then all possible case of two letters are: aa,ab,ba,bb.
If I have a word "abc" then all possible case of three letters are: aaa,bbb,aab,bba,aba, ccc,cbc,cac,acc,bcc,ccb,cca,bab,abc,acb,bac,bca,cab,cba.