Skip to content

Instantly share code, notes, and snippets.

@beezee
Created March 19, 2012 18:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save beezee/2123957 to your computer and use it in GitHub Desktop.
Save beezee/2123957 to your computer and use it in GitHub Desktop.
caclulate every possible combination of n words up to x from a string
var nGramr = {}
nGramr.words = prompt('Whats the phrase?').split(' ');
nGramr.wordlen = nGramr.words.length;
nGramr.depth = prompt('Whats the n?');
nGramr.results = 0;
nGramr.grams = function(aWords) {
var words = aWords;
var depth = words.length;
console.log(depth);
_.each(nGramr.words, function(word) {
if (words.indexOf(word) == -1) {
console.log(words.join(' '), word);
nGramr.results ++;
var nextCall = words.slice(0);
nextCall.push(word);
if (depth < nGramr.depth - 1) nGramr.grams(nextCall);
}
});
};
_.each(nGramr.words, function(word) {
nGramr.grams([word]);
});
console.log(nGramr.results + ' results');
@beezee
Copy link
Author

beezee commented Mar 19, 2012

because it took me 4 hours out of my weekend to realize i had to properly clone the words array before recursing... so i will never forget this lesson

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment