13
I did a job for compute all combinations of an array. The problem with my approach is that it only "generates" three-digit combinations (array length past 3), since I have 3 nested loops. If I wanted, however, that it generates values with 4 digits, I would have to nest one more loop.
Is there any way to create this same function, but recursively so that I can pass an argument by specifying the number of characters?
The expected result is an array of length L ^ N
, being L
the length of the array passed and N
the number of characters per combination.
const data = ['a', 'b', 'c'];
function all(data) {
const final = [];
for (const c1 of data) {
for (const c2 of data) {
for (const c3 of data) {
final.push(c1 + c2 + c3);
}
}
}
return final;
}
const x = all(data);
console.log(x.length, ':' , x);
Take a look at this code here, it might clear up your idea https://www.devmedia.com.br/permutacoes-objetos-um-algoritmo-recursivo-em-java/27512
– luizricardo6n