I have been trying to recreate the JavaScript version of this C program .
The program is suppose to generate all possible combinations from the characters in the array set.
Basically there are two functions printAllKeyLength and printAllKeyLengthR.Each
time the second function is called , it checks for k variable which upon equal to 0 prints the result.
The for loop within it iterates through length of the character set and appends each char to a variable prefix and variable new prefix. After that it calls itself repeatedly until each variant of it results in the k variable of it equal to zero. The C program works fine but the JavaScript completes only through the last few calls of the function which results in incomplete result. The rest previous calls are omitted.I tried changing the JavaScript functions to async function but didn't work out.Can any one explain why this is happening and how to fix it without changing the functions and structure of the program entirely ?
[C Language] --- This works fine but not the JavaScript Version { below }
#include <stdio.h>
#include <string.h>
int c = 0, chct;
char subs[10];
char set0[27] = "";
void
printallkeylengR(char set[], char prefix[], int n, int k)
{
if (k == 0) {
printf("%s\n", prefix);
}
else {
for (int i = 0; i < n; i++) {
char newprefix[10] = "";
char tmp[2] = "";
tmp[0] = set[i];
strcpy(subs, prefix);
strcat(prefix, tmp);
strcpy(newprefix, prefix);
strcpy(prefix, subs);
printallkeylengR(set, newprefix, n, k - 1);
}
}
}
void
printallkeyleng(char set[], int k, int n)
{
char ch[1] = "";
printallkeylengR(set, ch, n, k);
}
int
main()
{
chct = 0;
for (int i = 65; i <= 90; i++) {
set0[chct] = i;
chct += 1;
}
set0[27] = '\0';
printallkeyleng(set0, 4, strlen(set0));
return 0;
}
[Javascript] --- Does not iterate through all the results !!!
function printAllKeyLengthR(set,prefix,n,k){
if(k==0){
document.body.appendChild(document.createTextNode(prefix+" "));
}
else{
console.log("Prefix "+prefix+" K= "+k)
for(i=0;i<n;i++){
newprefix=prefix.toString()+set[i].toString();
console.log("New Prefix "+newprefix+" K= "+k+" i= "+i);console.log(" ");
const x = printAllKeyLengthR(set,newprefix,n,k-1)
}
}
}
function printAllKeyLength(set,k,n){
printAllKeyLengthR(set,"",n,k);
}
set=["0","1","2","3","4","5","6","7","8","9"];
//printAllKeyLength(set ,final_length,no_of_elem)
printAllKeyLength(set,4,10)