Take a look at this jsFiddle for a working example.
function shortAndLong(QATree, startNode) {
var paths = [];
function findAllPaths(startNode, currentCost) {
for (var i = 0; i < startNode.answers.length; i++) {
var child = startNode.answers[i];
if (child.nextQuestion == null) {
paths.push(currentCost);
}else {
findAllPaths(QATree[child.nextQuestion], currentCost+1);
}
}
}
findAllPaths(startNode, 1);
return [Math.min.apply(Math, paths), Math.max.apply(Math, paths)]
}
console.debug('ans',shortAndLong(QAndAObj, QAndAObj[1]));//returns [2, 4]
console.debug('ans',shortAndLong(QAndAObj, QAndAObj[2]));//returns [1, 3]
console.debug('ans',shortAndLong(QAndAObj, QAndAObj[3]));//returns [1, 2]
console.debug('ans',shortAndLong(QAndAObj, QAndAObj[4]));//returns [1, 1]
The basics are
- Create a list of all paths through the graph, keeping the number of answers needed
- Find max and min