Skip to content

Instantly share code, notes, and snippets.

@kennyt
Last active August 29, 2015 14:23
Show Gist options
  • Save kennyt/73f71cd563a978b51eda to your computer and use it in GitHub Desktop.
Save kennyt/73f71cd563a978b51eda to your computer and use it in GitHub Desktop.
var getAllPermutations = function(str){
if(str.length < 2){
return [str];
}
var result = [];
for(var i = 1; i < str.length + 1; i++){
var beginning = [str.slice(0, i)];
var rest = getAllPermutations(str.slice(i));
for(var j = 0; j < rest.length; j++){
result.push(beginning.concat(rest[j]));
}
}
return result;
};
var getAllAdditionSubtraction = function(nums){
if(nums.length === 1){
return nums;
} else if (nums.length === 2){
return [nums[0] - nums[1], nums[0] + nums[1]];
}
var rest = getAllAdditionSubtraction(nums.slice(0, nums.length - 1));
var last = nums[nums.length - 1];
var result = [];
for(var i = 0; i < rest.length; i++){
var single = rest[i];
result.push(single + last);
result.push(single - last);
}
return result;
};
var main = function(num){
var permutations = getAllPermutations(num.toString()).map(function(str){
return str.filter(function(chr){
return chr !== "";
}).map(function(num){
return Number(num);
});
});
var result = [];
permutations.forEach(function(perm){
result = result.concat(getAllAdditionSubtraction(perm));
});
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment