Created
September 9, 2014 22:35
-
-
Save eiriklv/870a6f6211b0c9bad471 to your computer and use it in GitHub Desktop.
Create all possible combinations from a dictionary
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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