I understand what permutations are yet I still can’t understand what the goal of this challenge is.
In the list of what results should be achieved I can’t understand where those results are coming from.
In the list of permutations of “aab”, I don’t understand why each one of the three permutations is listed twice to get six.
These are not permutations as term is used in combinatorics. Then it could be solved very simply (you’ve already implemented the factorial operation in an earlier challenge). The fact that each letter must be treated as unique (as @rmdawson71 explained) is what makes this one a beast.
If it’s any consolation, this one really took me an embarrassingly long time to figure out.
At one point I put a lot of comments in my solution for another camper, so I’m going to include that solution here for anyone who wants to go looking for a way to solve this.
Spoiler
/* First pass at No Repeats Please
* Creates an array of all permutations then filters out strings with repeated letters
*/
function permAlone(str) {
if (typeof str !== 'string') return undefined; // invalid input
var charArray = str.split('');
var permArray = generatePerms('', charArray);
permArray = permArray.filter(function(val) {
// For more information about this look at
// https://regex101.com/r/c3j241/1 and
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test
return !(/(\w)\1/.test(val));
});
return permArray.length;
}
// Recursive function to generate all permutations (see graphic representation below)
function generatePerms(str, remaining) {
var results = [];
// only one letter left to add
if (remaining.length === 1) {
results = [str + remaining[0]];
}
// recursive case
else if (remaining.length > 1) {
for(var i = 0; i < remaining.length; i++){
var newRemaining = remaining.slice(); // create a copy by value
newRemaining.splice(i,1);
results = results.concat(generatePerms(str + remaining[i], newRemaining));
}
}
return results;
}
permAlone('aab');
/////////GRAPHIC REPRESENTATION OF generatePerms//////////////////
// [a,b,a]
//
// / | \
// / | \
// / | \
// | |
// a[b,a] b[a,a] a[a,b]
// / \ / \ / \
// ab[a] aa[b] ba[a] ba[a] aa[b] ab[a]
// | | | | | |
// aba aab baa baa aab aba