Sunday 31 October 2021

Find all possible combinations of strings that match a given pattern in JS

So I have a dictionary where each key is mapped to an array of letters:

tCategories = { "T": ["t","d","th"],
                "P": ["p","t","k","q"],
                "N": ["m","n"] };

And an input string that contains a handful of patterns delimited by commas, e.g. "aT,Ps,eNe,NP", where a substring that is a valid key of tCategories acts a stand-in for any of the letters in tCategories[key].

What I'm trying to figure out is how to find every combination of each pattern listed in the input string and put them all in an array. So e.g. the expected output for foo("aT,Ps,eNe,NP") would be ["at","ad","ath","ps","ts","ks","qs","eme","ene","mp","mt","mk","mq","np","nt","nk","nq"].

My first instinct would either be to call String.split(",") on the input string to deal with each substring separately, or else iterate via for (var key in tCategories) { input.replace(new RegExp(key, "g"), "["+tCategories[key].join("|")+"]" }, or something... but I just can't seem to find a useful pathway between those and the expected output. It would involve... what, basically implementing the distributive property but for letters instead of numbers? How do I do this?



from Find all possible combinations of strings that match a given pattern in JS

No comments:

Post a Comment