I have to code a tool which will allow business users to create a survey. Some questions should only be asked if the person filling the survey answered the previous questions in a specific way. But some questions should be displayed, whatever the chosen answer is.
Thus far, I came up with a graph structure, here is a theoretical example of what it would look like:
(I only have a basic knowledge of graph theory so please excuse the choice of word which might not be as accurate as it could be)

The rounds like A,B,C represent questions and the value on the links represent the precondition to access the question.
NULL means that there are no precondition and a value like "0" or "1" means that the previous question must have an answer with the value "0" or "1" to display the question.
Concrete example: I'm at round A. I have two possible answer. The first one has a value of "0". The second, a value of "1". If I choose the answer with value "0" then I will go to question B.
I'm now at round B. Whatever the answer is, I will go to round E because there are no precondition.
E is a leaf node, so I go back to B. B has another child node F with no precondition so I move to question F. Let's end the flow there.
I can also have one question that has multiple precondition. This is represented by question N. It can only be accessed if the answer is "5" on question F and "DE" on question I. In this case, after answering question F, since only one precondition is valid at this state, we will go back up in the graph and it's only after answering "DE" on question I that we can then move to question N.
My question is about the algorithm to use for such a survey. Is there an existing algorithm covering this use case ? I thought this looks like a DFS graph traversal but the conditionals make me doubt.
Also, am I overcomplicating things and can this be expressed much more simply ? I'd really like some advice at this stage.
Thanks for your help !
According to your description, I would change slightly the concept of the graph you have proposed to the following:
Then the algorithm would go along the following lines:
This should reproduce the order that you describe. If you want to have the ability to have several possible unlocking answers (e.g. "from A you would go to B if you answer 1 or 2") you would need to do some more tweaking (namely, in step 6 you would need to replace the "visited" check for "answer type" predecessors of R to something like "R is reachable through visited nodes from the predecessor of the predecessor of R"), but it should still be possible to get it to work.
Maybe you already know about it, but if you are interested in using a graph as your only data source (which may or may not be the case), you might find interesting graph-oriented databases like Neo4j.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With