I've got a two dimensional array of synonyms (or rather, equivalent) words; and a given sentence. I need to return an array of sentences that contain all permutations of words replaced with their synonyms.
Example, given synonyms/equivalences array:
const eqs = [
['hi', 'hello', 'hey'],
['programmer', 'coder']
]
And
const sentence = 'hello programmer'
Return (order is not important):
['hello programmer',
'hi programmer',
'hey programmer',
'hello coder',
'hi coder',
'hey coder']
I'm not able to find all possible permutations, only some. Here's what I have + Codepen demo
const getAllEquivalentSentences = (sentence, eqs) => {
const eqSentences = new Set([sentence])
sentence.split(/\s/).forEach(word => {
// current is an array of equivalent terms, or array
// with a single item
const curr = eqs.find(row => row.includes(word)) || [word]
curr.forEach(wordEq => {
if (wordEq !== word) {
eqSentences.add(sentence.replace(word, wordEq))
}
})
})
return [...eqSentences]
}
Seems like I'll need a dynamic programming solution, but that's getting too complex for me too fast. Is there a simpler approach that I'm missing?