Answer the question
In order to leave comments, you need to log in
How do permutations (arrays) work?
Я не понимаю как работает код в finalPermutations.
Я закомментировал часть кода, которую я не понимаю
function permutations(string) {
if (string.length <= 1) {
return [string];
}
let finalPermutations = permutations(string.substring(1)) // ?
.reduce((acc, p) => {
let charList = p.split('');
for (let i = 0; i <= charList.length; i++) { // ?
let newPermutation = charList.slice(0, i) // ?
.concat([string[0]]) // ?
.concat(charList.slice(i)) // ?
.join('');
if (!acc.includes(newPermutation)) { // ?
acc.push(newPermutation); // ?
}
}
return acc;
},[]);
return finalPermutations;
}
Answer the question
In order to leave comments, you need to log in
This is a recursive method for generating all permutations. First, permutations are generated recursively for all characters except the first one. Then, for each permutation, the first character is inserted in each possible position.
So, to generate all the permutations of "abc", first the array {"bc", "cb"} will be recursively obtained, then for each element in the answer, a permutation with "a" inserted in positions 0, 1 and 2 will be added: "abc ", "bac", "bca" for the first element, and "acb", "cab" and "cba" for the second.
Or do you not understand what reduce, slice, substring, concat, join do?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question