Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate a random math Equation using Random numbers and operators in Javascript

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

The game must produce equations with addition + and multiplication * operators like ( 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

Input would be form : for example

level 3

Output should be:

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

So far i can create equations without brackets but i need help that would give me 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
    }  
}
like image 216
david warne Avatar asked Oct 04 '15 17:10

david warne


1 Answers

I picked up the idea of @plamut to create a binary tree, where each node represents an operator with a left and a right side.

For instance, the equation 2 * (3 + 4) can be seen as

  *
 / \
2   +
   / \
  3   4

You can represent this quite straight forward 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-tree would have half of the desired total number of nodes (= length of 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.

Maybe you still want to care about special cases, like avoiding brackets at top level, but that shouldn't be too hard from here.

like image 67
Cedric Reichenbach Avatar answered Sep 18 '22 14:09

Cedric Reichenbach