Skip to content

Instantly share code, notes, and snippets.

@dva
Created September 25, 2014 20:10
Show Gist options
  • Select an option

  • Save dva/6a986e27e6f67dbbb56b to your computer and use it in GitHub Desktop.

Select an option

Save dva/6a986e27e6f67dbbb56b to your computer and use it in GitHub Desktop.
// Permutation
function permute(input) {
var permArr = [],
usedChars = [];
function main(input) {
var i, ch;
for (i = 0; i < input.length; i++) {
ch = input.splice(i, 1)[0];
usedChars.push(ch);
if (input.length === 0) {
permArr.push(usedChars.slice());
}
main(input);
input.splice(i, 0, ch);
usedChars.pop();
}
return permArr;
}
return main(input);
}
// Combinations
var follows, combinations;
follows = function(a) {
return a.map(function(item, i) {
return [item, follows(a.slice(i+1))];
});
};
combinations = function(a) {
var combs = function(prefix, trie, result) {
trie.forEach(function(node, i) {
result.push((prefix + ' ' + node[0]).trim());
combs(prefix + ' ' + node[0], node[1], result);
});
// return result;
// return result.sort(function(a,b){return b-a});
return result.sort(function(a,b){return b.length - a.length;});
};
return combs('', follows(a), []);
};
console.log('Permutation', permute([5, 3, 7, 1]));
console.log('Combination', combinations([5, 3, 7, 1]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment