Tree management optimization

I need to create reports based on user input. The user answers the question, and then, depending on the answer, I go left or right in the tree structure and ask a new question. Some nodes will have the same question, but different children. I'm not sure what would be the best way to do this in terms of code readability?

I would like to avoid a huge management structure, as this would be extremely unreadable, for example:

if() { if() { if() { if() { ... } } else { if() { ... } } } else { ... } } else { if() { if() { if() { ... } } else { if () { ... } } } } 

Is there a better way to handle this? Here is an image of what my tree looks like

enter image description here

+6
source share
2 answers

Store the tree as data, and then your code can be very small. If we change the answer given by @ jam6549, we can come up with something like this:

 var answer = [ {t: "Does it have fur?", y: 1, n: 2}, {t: "Is it a kitten?", y: 3, n: 4}, {t: "Is it a goldfish?", y: 5, n: 4}, {t: "Found a kitten", y: -1, n: -1}, {t: "I'm stumped", y: -1, n: -1}, {t: "Found a goldfish", y: -1, n: -1} ]; var state = 0; while ( answer[state].y >= 0 ) { var choice = confirm(answer[state].t); state = choice? answer[state].y: answer[state].n; } alert(answer[state].t); 

This only supports simple y / n answers, so I can use confirmation, you will want to use an array with a record for every possible answer.

You say that some of the questions are repeated, so I will be tempted to have an array with each unique question text. Your answer array then stores the index in the question array to preserve duplicate text.

+2
source

If you are using mysql, just ask for a table for questions and a table for such answers:

Question table:

 +----------+-----------+ | id | question | +----------+-----------+ | 1 | Question 1| +----------+-----------+ | 2 | Question 2| +----------+-----------+ | 3 | Question 3| +----------+-----------+ 

Answer table:

 +----------+-----------+-----------+---------------+ | id | answer | question | next_question | +----------+-----------+-----------+---------------+ | 1 | Answer 1 | 1 | 2 | +----------+-----------+-----------+---------------+ | 2 | Answer 2 | 1 | 3 | +----------+-----------+-----------+---------------+ 

If the user is on question 1 and selects the first answer, he goes to question 2. If they choose the second answer, they go to question 3.

So, in your code, just query the database after each response using id:

 SELECT next_question FROM answers WHERE id = ?; // Change '?' depending on answer to get next question 

Then get the following answers:

 SELECT answer FROM answers WHERE question = ?; // Change '?' depending on previous value retrieved 

Hope this helps.

+2
source

All Articles