Print all permutations of a given string.
Begin at the first letter.
Continue this process for each position in the word. Once we've reached the end of the word, we have found one complete arrangement (permutation).
output = []
def permute(ls, idx):
if idx == len(ls) - 1:
output.append("".join(ls))
return
for i in range(idx, len(ls)):
ls[idx], ls[i] = ls[i], ls[idx]
permute(ls, idx + 1)
ls[idx], ls[i] = ls[i], ls[idx]
str = "abc"
permute(list(str), 0)
print(output)
const output = [];
function permute(list, idx) {
if (idx === list.length) {
output.push(list.join(""));
return;
}
for (let i = idx; i < list.length; i++) {
[list[idx], list[i]] = [list[i], list[idx]];
permute(list, idx + 1);
[list[idx], list[i]] = [list[i], list[idx]];
}
}
const str = "abc";
permute(str.split(""), 0);
console.log(output);