Skip to content

Instantly share code, notes, and snippets.

@line-o
Forked from usefulthink/bt-search.coffee
Created January 27, 2012 09:17
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 line-o/1687912 to your computer and use it in GitHub Desktop.
Save line-o/1687912 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=['H','He','Li','Be','B','C','N','O','F','Ne','L','Na','Mg','Al','Si','P','S','Cl','Ar','M','K','Ca','Sc','Ti','V','Cr','Mn','Fe','Co','Ni','Cu','Zn','Ga','Ge','As','Se','Br','Kr','N','Rb','Sr','Y','Zr','Nb','Mo','Tc','Ru','Rh','Pd','Ag','Cd','In','Sn','Sb','Te','I','Xe','O','Cs','Ba','Hf','Ta','W','Re','Os','Ir','Pt','Au','Hg','Tl','Pb','Bi','Po','At','Rn','P','Fr','Ra','Rf','Db','Sg','Bh','Hs','Mt','Ds','Rg','Cn','Uut','Uuq','Uup','Uuh','Uus','Uuo','Q','La','Ce','Pr','Nd','Pm','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb','Lu','Ac','Th','Pa','U','Np','Pu','Am','Cm','Bk','Cf','Es','Fm','Md','No','Lr'],
rest='FNORD'
)
))
(function() {
var c = [],
els = ['H','He','Li','Be','B','C','N','O','F','Ne','L','Na','Mg','Al','Si','P','S','Cl','Ar','M','K','Ca','Sc','Ti','V','Cr','Mn','Fe','Co','Ni','Cu','Zn','Ga','Ge','As','Se','Br','Kr','N','Rb','Sr','Y','Zr','Nb','Mo','Tc','Ru','Rh','Pd','Ag','Cd','In','Sn','Sb','Te','I','Xe','O','Cs','Ba','Hf','Ta','W','Re','Os','Ir','Pt','Au','Hg','Tl','Pb','Bi','Po','At','Rn','P','Fr','Ra','Rf','Db','Sg','Bh','Hs','Mt','Ds','Rg','Cn','Uut','Uuq','Uup','Uuh','Uus','Uuo','Q','La','Ce','Pr','Nd','Pm','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb','Lu','Ac','Th','Pa','U','Np','Pu','Am','Cm','Bk','Cf','Es','Fm','Md','No','Lr'],
rest = 'PUNK',
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.toUpperCase()) === 0) {
_results.push(searchCombination(c.concat([el]), els, rest.slice(el.length)));
}
}
return _results;
};
console.log(JSON.stringify(searchCombination(c, els, rest)));
}).call(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment