I chose the @plamut idea for creating a binary tree, where each node is an operator with left and right sides.
For example, the equation 2 * (3 + 4) can be considered as
* / \ 2 + / \ 3 4
You can imagine this quite straightforwardly using objects as follows:
var TreeNode = function(left, right, operator) { this.left = left; this.right = right; this.operator = operator; this.toString = function() { return '(' + left + ' ' + operator + ' ' + right + ')'; } }
Then you can create a recursive function to build such trees, where one sub-element will have half the required total number of nodes (= length of the equation):
function buildTree(numNodes) { if (numNodes === 1) return randomNumberRange(1, 100); var numLeft = Math.floor(numNodes / 2); var leftSubTree = buildTree(numLeft); var numRight = Math.ceil(numNodes / 2); var rightSubTree = buildTree(numRight); var m = randomNumberRange(0, x.length); var str = x[m]; return new TreeNode(leftSubTree, rightSubTree, str); }
Here's a JSFiddle with a working example.
You may still want to take care of special cases, for example, to avoid parentheses at the top level, but it should not be too difficult from here.
source share