Reputation: 365
I'm trying to write a function that can perform permutation.
For example, if I input [1, 2, 3]
, the expected answer will be
[ [ 3, 2, 1 ], [ 3, 2, 1 ],[ 3, 2, 1 ],[ 3, 2, 1 ],[ 3, 2, 1 ],[ 3, 2, 1 ] ]
But instead of showing the answer, it returns [[ ],[ ],[ ],[ ],[ ]]
Any ideas?
var permute = (nums) => {
results = [];
var backtrack = (nums, result) => {
if (nums.length === result.length) {
results.push(result);
} else {
for (var i = 0; i < nums.length; i++) {
if (result.indexOf(nums[i]) > -1) {
continue;
}
result.push(nums[i]);
backtrack(nums, result);
result.pop();
}
}
}
backtrack(nums, []);
return results;
};
console.log(permute([1, 2, 3]));
Upvotes: 5
Views: 164
Reputation: 5260
Just Another approach using reverse(), an special case of permutation which OP gives as an example:
var arr = [ [ 3, 2, 1 ], [ 3, 2, 1 ],[ 3, 2, 1 ],[ 3, 2, 1 ],[ 3, 2, 1 ],[ 3, 2, 1 ] ];
var permuted = arr.map((num) => {
return num.reverse();
});
console.log(permuted);
Upvotes: 0
Reputation: 386746
You could take a local copy of result
by slicing this array to prevent the same object reference in the result set.
var permute = (nums) => {
var results = [];
var backtrack = (nums, result) => {
if (nums.length === result.length) {
results.push(result.slice()); // push copy
} else {
for (var i = 0; i < nums.length; i++) {
if (result.indexOf(nums[i]) > -1) {
continue;
}
result.push(nums[i]);
backtrack(nums, result);
result.pop();
}
}
};
backtrack(nums, []);
return results;
};
console.log(permute([1, 2, 3]).map(a => a.join(' ')));
A version without pushing and popping.
var permute = (nums) => {
var results = [];
var backtrack = (nums, result) => {
if (nums.length === result.length) {
results.push(result);
} else {
for (var i = 0; i < nums.length; i++) {
if (result.indexOf(nums[i]) > -1) {
continue;
}
backtrack(nums, result.concat(nums[i])); // use a new array
}
}
};
backtrack(nums, []);
return results;
};
console.log(permute([1, 2, 3]).map(a => a.join(' ')));
Upvotes: 5