Skip to content

Instantly share code, notes, and snippets.

@usefulthink
Created January 27, 2012 09:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save usefulthink/1687902 to your computer and use it in GitHub Desktop.
Save usefulthink/1687902 to your computer and use it in GitHub Desktop.
backtracking combinator
# searches a combination of the given elements that matches toMatch
# @param c array - initially empty, carries the current combination throught
# the recursion
# @param els array - the predefined set of elements
# @param toMatch string - the rest-string to be matched with the elements
#
# @return an array of combinations that recursively match
searchCombination = (c, els, rest) ->
return c if rest.length==0
searchCombination(c.concat([el]), els, rest.slice(el.length)) \
for el in els when rest.indexOf(el) == 0
# test
console.log(JSON.stringify(
searchCombination(
c=[],
els=['F', 'FN', 'O', 'R', 'RD', 'D'],
rest='FNORD'
)
))
(function() {
var c, els, rest, searchCombination;
searchCombination = function(c, els, rest) {
var el, _i, _len, _results;
if (rest.length === 0) return c;
_results = [];
for (_i = 0, _len = els.length; _i < _len; _i++) {
el = els[_i];
if (rest.indexOf(el) === 0) {
_results.push(searchCombination(c.concat([el]), els, rest.slice(el.length)));
}
}
return _results;
};
console.log(JSON.stringify(searchCombination(c = [], els = ['F', 'FN', 'O', 'R', 'RD', 'D'], rest = 'FNORD')));
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment