Skip to content

Instantly share code, notes, and snippets.

@eiriklv
Created September 9, 2014 22:35
Show Gist options
  • Save eiriklv/870a6f6211b0c9bad471 to your computer and use it in GitHub Desktop.
Save eiriklv/870a6f6211b0c9bad471 to your computer and use it in GitHub Desktop.
Create all possible combinations from a dictionary
// create combination from a dictionary
function combination(dictionary, length, depth, input, output) {
// check if this is the original call and instantiate the helpers
if (!depth) {
output = [];
input = '';
depth = 0;
}
// loop through the dictionary to create combinations
dictionary.forEach(function(element) {
if (depth == length - 1) {
output.push(input + element);
} else {
combination(dictionary, length, depth + 1, input + element, output);
}
});
// return value from original function call
if (!depth)
return output;
// return to exit from recursive function call
return;
}
// dictionary to create combinations from
var dictionary = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
// all combinations with 4 letters
var comb = combination(dictionary, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment