From c849ae308d0ebe96bee0369325cd544f6cb5a5f6 Mon Sep 17 00:00:00 2001 From: Aerex Date: Tue, 18 Feb 2020 10:32:25 -0600 Subject: [PATCH] feat: Added permutations problem in js --- permutations/nodejs/index.js | 58 ++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 permutations/nodejs/index.js diff --git a/permutations/nodejs/index.js b/permutations/nodejs/index.js new file mode 100644 index 0000000..249352b --- /dev/null +++ b/permutations/nodejs/index.js @@ -0,0 +1,58 @@ +/* + * Given a collection of distinct integers, return all possible permutations. + * Example: + * + * Input: [1,2,3] + * Output: + * + * [ + * [1,2,3], + * [1,3,2], + * [2,1,3], + * [2,3,1], + * [3,1,2], + * [3,2,1] + * + * ] +*/ + +const { assert } = require('../../util/js'); + +/** + * @param {number[]} nums + * @return {number[][]} + */ +const permute = function(nums) { + + const permuRecursive = (soFar, rest, perm) => { + if (rest.length === 0) { + perm.push(soFar); + } + + for(let i = 0; i < rest.length; i++) { + const rem = [...rest.slice(0, i), ...rest.slice(i+1)]; + permuRecursive([...soFar, rest[i]], rem, perm); + } + } + const result = []; + permuRecursive([], nums, result); + return result; + +}; + +/* Test Case 1 + * Input: [1,2,3] + * Output: + * [ + * [1,2,3], + * [1,3,2], + * [2,1,3], + * [2,3,1], + * [3,1,2], + * [3,2,1] + * + * ] + */ +x = [1,2,3]; +sol = [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]; +assert(JSON.stringify(permute(x)) === JSON.stringify(sol), `Output: ${JSON.stringify(sol)}`);