From 4fd944f2d5c68bf78caddb7288ed8c4363cf6991 Mon Sep 17 00:00:00 2001 From: AmourRamanantsiresy Date: Thu, 6 Oct 2022 14:33:27 +0300 Subject: [PATCH] chore: string permutation --- String permutation/permutation.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 String permutation/permutation.js diff --git a/String permutation/permutation.js b/String permutation/permutation.js new file mode 100644 index 0000000..c9d40d3 --- /dev/null +++ b/String permutation/permutation.js @@ -0,0 +1,29 @@ +/** + * There is a given string input and + * this script will create all permutations of this string. + * + * * With input 'aabb' + * * Thre result will be ['aabb', 'abab', 'abba', 'baab', 'baba', 'bbaa'] + * + */ + +let input = 'aabb'; + +// variable that will store all permutations +let permutations = []; +function permute(str, arr) { + if (arr.length == 0 && !permutations.includes(str)) { + permutations.push(str); + } else { + for (let i = 0; i < arr.length; i++) { + let arr2 = arr.slice(); + arr2.splice(i, 1); + permute(str + arr[i], arr2); + } + } +} + +// call the function for the permutation +permute('', input.split('')); +// print the result +console.log(permutations);