How to print all possible permutations (all possible orderings) of the words in TypeScript

1 Answer

0 votes
function print_words_permutations(words: string[], current: string[] = []): void {
    if (words.length === 0) {
        console.log(current.join(" "));
        return;
    }

    words.forEach((word: string, i: number) => {
        const remaining: string[] = words.slice(0, i).concat(words.slice(i + 1));
        print_words_permutations(remaining, [...current, word]);
    });
}

const words: string[] = ["word-1", "word-2", "word-3"];

print_words_permutations(words);



/*
run:

word-1 word-2 word-3
word-1 word-3 word-2
word-2 word-1 word-3
word-2 word-3 word-1
word-3 word-1 word-2
word-3 word-2 word-1

*/

 



answered Apr 14 by avibootz

Related questions

...