Skip to content

Instantly share code, notes, and snippets.

@deepakshrma
Last active December 1, 2020 10:09
Show Gist options
  • Save deepakshrma/3c2d2daf047de971070f6a9dbf2efce7 to your computer and use it in GitHub Desktop.
Save deepakshrma/3c2d2daf047de971070f6a9dbf2efce7 to your computer and use it in GitHub Desktop.
const permutation = text => {
return permute("", text);
};
const permute = (prefix, sufix, arr = []) => {
if (sufix.length == 0) arr.push(prefix);
else {
for (let i = 0; i < sufix.length; i++) {
permute(
prefix + sufix.charAt(i),
sufix.substr(0, i) + sufix.substr(i + 1),
//sufix.substr(0, i) + sufix.substr(i + 1, sufix.length),
arr
);
}
}
return arr;
};
console.log(permutation("ABCD"));
const permutation = (arr) => {
return permute([], arr);
};
const permute = (prefix, suffix, arr = []) => {
if (suffix.length == 0) arr.push(prefix);
else {
for (let i = 0, len = suffix.length; i < len; i++) {
permute(
[...prefix, suffix[i]],
[...suffix.slice(0, i), ...suffix.slice(i + 1)],
arr
);
}
}
return arr;
};
console.log(permutation(["A", "B", "C"]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment