Reputation: 13
I want to make a functions that prints all the possible combinations from the given string. example: given_string = "ABC" this should print: AAA AAB AAC ABA ABB ABC .. and so on, until it reaches maximum options. CCC
I found some code on the web and modified it for JS
s = ["A", "B", "C"]
function printAllKLength(set, k) {
n = set.length;
printAllKLengthRec(set, "", n, k);
}
function printAllKLengthRec(set, prefix, n, k) {
if (k == 0) {
console.log(prefix);
return;
}
for (i = 0; i < n; i++) {
newPrefix = prefix + set[i];
printAllKLengthRec(set, newPrefix, n, k - 1);
}
}
printAllKLength(s, 4)
It only changes the last character and I don't understand where is my mistake. original code URL: https://www.geeksforgeeks.org/print-all-combinations-of-given-length/
Upvotes: 1
Views: 420
Reputation: 50797
Another answer already demonstrated how to fix your code. But I just want to point out a simpler recursion to calculate these values, leaving the printing for a separate step:
const allCombos = (n, xs) =>
n == 0
? ['']
: allCombos (n - 1, xs) .flatMap (c => xs. map(x => c + x))
console .log (
allCombos (3, ['A', 'B', 'C']),
)
.as-console-wrapper {min-height: 100% !important; top: 0}
For n
-character strings, we simply recur on n - 1
characters, and for each of those, map over the characters, appending each to the string. When n
is 0
, we simply return an array containing the empty string.
Upvotes: 0
Reputation: 10030
While declaring your variables, you have missed out on using the var
keyword and especially before declaring i
in the for
statement. It's important since variables without var
keyword are defined in global scope and each recursive call is using the same i
variable for the for
loop. That's the reason it generates very few possibilities. See the fixed code below:
s = ["A", "B", "C"]
function printAllKLength(set, k) {
n = set.length;
printAllKLengthRec(set, "", n, k);
}
function printAllKLengthRec(set, prefix, n, k) {
if (k == 0) {
console.log(prefix);
return;
}
for (var i = 0; i < n; i++) {
// ^^^ Notice var, it scopes the variable to the function otherwise, it will be global
newPrefix = prefix + set[i];
printAllKLengthRec(set, newPrefix, n, k - 1);
}
}
printAllKLength(s, 4)
Upvotes: 3