Generate a random math equation using random numbers and operators in Javascript

I want to create a program that needs to print the simplest form of mathematical expression as (21 + 13) * 56 using Random No. 1 to 100 . The program must take a level parameter, level determines the length of the generated equation, for example:

In the game, equations with the addition of + and multiplication operators * must be created, such as (21 + 13) * 56. (using brackets)

----level 2 75 - 54 = 21 62 + 15 = 77 88 / 22 = 4 93 + 22 = 115 90 * 11 = 990 --level 3 ( 21 + 13 ) * 56 = 1904 82 - 19 + 16 = 79 51 * ( 68 - 2 ) = 3366 

The input will take the form: for example

 level 3 

The conclusion should be:

 ( 21 + 13 ) * 56 // Simple expression using Random no.s 

While I can create equations without brackets, but I need help that will give me a reliable solution.

This is what I have done so far:

 var input = 'level 3' input = input.split(' ') var n = Number(input[1]) var x = ['/','*','-','+'] function randomNumberRange(min, max) { return Math.floor(Math.random() * (max - min) + min); } var a = '' for(var i=0;i<n;i++){ if(i !== n-1){ var n1 = randomNumberRange(1, 100) var m = randomNumberRange(0, x.length); var str = x[m]; a += n1 a +=' '+str+' ' }else{ a += n1 } } 
+6
source share
1 answer

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.

+3
source

All Articles