I am trying to make a list of all possible letter cases of the first letter of the words in a sentence. I can however not think of a way to do this in code because I have no idea how to check for the permutations
For Example:
Sentence: "A short sentence"
Result: (A Short Sentence, a short sentence, A short sentence, a Short sentence, a short Sentence, A short Sentence, A Short sentence, a Short Sentence);
The order doesn't matter. A sentence can be any length. NO punctuation in sentences or results is entered.
I know this will require some pc power for longer strings.
CodePudding user response:
Introducing a concept of recursion with idea that assuming you have a list of a shorter array, you can add a word
and a Word
to the beginning of each of those to get the "true" list.
var str = "A short sentence"
var arr = str.split(" ")
function lcase(word) {
return word.substr(0, 1).toLowerCase() word.substr(1)
}
function ucase(word) {
return word.substr(0, 1).toUpperCase() word.substr(1)
}
// lets go
function lista(arr) {
if (arr.length == 0) {
return []
}
var first = lcase(arr[0]);
var First = ucase(first)
if (arr.length == 1) {
return [first, First];
}
var list = lista(arr.slice(1))
var result = [];
list.forEach(function(a) {
result.push(([first].concat(a)).join(" "))
result.push(([First].concat(a)).join(" "))
})
return result;
}
var result = lista(arr)
console.log(result)