找到所有带有同义词的句子排列?

时间:2018-02-07 17:11:54

标签: javascript arrays algorithm

我有一个二维数组的同义词(或者更确切地说,等价的);和一个给定的句子。我需要返回一个句子数组,其中包含用同义词替换的所有单词的排列。

示例,给定同义词/等价数组:

const eqs = [
  ['hi', 'hello', 'hey'],
  ['programmer', 'coder']
]

并且

const sentence = 'hello programmer'

退货(订单并不重要):

['hello programmer',
 'hi programmer',
 'hey programmer',
 'hello coder',
 'hi coder',
 'hey coder']

我无法找到所有可能的排列,只有一些。这就是我拥有的东西+  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]
}

似乎我需要一个动态的编程解决方案,但这对我来说过于复杂太快了。我缺少一种更简单的方法吗?

0 个答案:

没有答案