-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpermutations.js
More file actions
28 lines (26 loc) · 994 Bytes
/
Copy pathpermutations.js
File metadata and controls
28 lines (26 loc) · 994 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const find_permutations = function(nums) {
result = [];
result.push([]);
nums.forEach (x=> {
let current = [];
result.forEach(arr => {
//NOTE: starting from zero going all the way upto end of the array
for (let i=0; i<=arr.length; i++) {
//splice updates the array, hence create a clone first
let temp = [...arr];
//splice (index, number of entries (will be zero in our case), the item to be inserted)
//Do not confuse with slice
temp.splice(i, 0, x);
current.push(temp);
}
});
//NOTE: push adds elements to the end of the array
//concat merges two arrays, and returns a "new" array
result = result.concat(current);
});
return result.filter(x=> x.length == nums.length);
};
result = find_permutations([1, 3, 5]);
result.forEach((permutation) => {
console.log(permutation);
});