In the solution of the challenge by fCC, there is a line in “generate” function:
permutations.push(arr.join(""));
I understand this function is based on Heap’s algoritm, however if I don’t use join method and only push array “arr” into array “permutation”, the position of “arr” is unchange for each recursion.
Can someone please expain the reason for me?
Here is the solution of the challenge by fCC:
function permAlone(str) {
// Create a regex to match repeated consecutive characters.
var regex = /(.)\1+/;
// Split the string into an array of characters.
var arr = str.split("");
var permutations = [];
var tmp;
// Return 0 if str contains same character.
if (str.match(regex) !== null && str.match(regex)[0] === str) return 0;
// Function to swap variables' content.
function swap(index1, index2) {
tmp = arr[index1];
arr[index1] = arr[index2];
arr[index2] = tmp;
}
// Generate arrays of permutations using the algorithm.
function generate(int) {
if (int === 1) {
// Make sure to join the characters as we create the permutation arrays
permutations.push(arr.join(""));
} else {
for (var i = 0; i != int; ++i) {
generate(int - 1);
swap(int % 2 ? 0 : i, int - 1);
}
}
}
generate(arr.length);
// Filter the array of repeated permutations.
var filtered = permutations.filter(function(string) {
return !string.match(regex);
});
// Return how many have no repetitions.
return filtered.length;
}
// Test here.
permAlone("aab");
**Your browser information:**
User Agent is: Mozilla/5.0 (Linux; Android 11; M2007J3SG) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.98 Mobile Safari/537.36
Challenge: No Repeats Please
Link to the challenge: