我如何编写这个算法来搜索问题树中的下一个问题? [英] How do I write this algorithm to search for the next question in a question tree?

查看:31
本文介绍了我如何编写这个算法来搜索问题树中的下一个问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力为此编写正确的算法.所以我有一个看起来像这样的问题树:

<预><代码>[{问题:问题1",答案:{是的": [{问题:问题1a",答案:[A",B"]}],否":空}},{问题:问题2",答案:[我同意"]}]

我有一个 responses 对象,它看起来像这样:

<预><代码>[{问题:问题1",回答:是"},{问题:问题1a",答案:B"},]

也可能是这样:

<预><代码>[{问题:问题1",答案:否"},]

现在我正在努力编写的代码是找出下一个问题应该是什么.responses 对象的上述两个示例都应该指向下一个问题 问题 2".

我想要一个像 getNextQuestion(questions, answers) 这样的函数,然后希望输出:

<代码>{问题:问题2",答案:[我同意"]}

我已经想出了如何树,但我不知道如何在必要时树.有人愿意帮忙吗?

解决方案

嗯,我可能已经用这段代码修复了它.到目前为止一切正常.

getCurrentQuestion(问题,回复){if (!responses.length || !questions.length) {返回 questions.length ?问题[0]:空}让 response = response.shift()让问题做 {问题 = questions.shift()} while (question.question !== response.question)let answer = question.answers[response.answer]返回 this.getCurrentQuestion(回答 || 问题,回答)||this.getCurrentQuestion(问题,回复)}

I've been struggling to write the correct algorithm for this. So I have a tree of questions that looks like this:

[
  {
    question: "Question 1",
    answers: {
      "yes": [
        {
          question: "Question 1a",
          answers: ["A", "B"]
        }
      ],
      "no": null
    }
  },
  {
    question: "Question 2",
    answers: ["I agree"]
  }
]

And I have a responses object, which could look something like this:

[
  { question: "Question 1", answer: "yes" },
  { question: "Question 1a", answer: "B" },
]

Or it could be this:

[
  { question: "Question 1", answer: "no" },
]

And now the code I'm struggling to write is to find out what the next question should be. The above two examples of the responses object should both point to the next question being "Question 2".

I'd like to have a function like getNextQuestion(questions, responses) which would then hopefully output:

{
  question: "Question 2",
  answers: ["I agree"]
}

I've figured out how to go down the tree, but I can't figure out how to go up the tree when that's necessary. Anybody willing to help?

解决方案

Hmm, I may have fixed it with this code. It's been working okay so far.

getCurrentQuestion(questions, responses) {
  if (!responses.length || !questions.length) {
    return questions.length ? questions[0] : null
  }

  let response = responses.shift()
  let question

  do {
    question = questions.shift()
  } while (question.question !== response.question)

  let answer = question.answers[response.answer]

  return this.getCurrentQuestion(answer || questions, responses)
    || this.getCurrentQuestion(questions, responses)
}

这篇关于我如何编写这个算法来搜索问题树中的下一个问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆