thielr7
thielr7

Reputation: 337

compare math equations prior to evaluation javascript

I'm running through algebra and attempting to create a JavaScript tester function which compares two equations and determines if they are considered associative properties. In other words, if I group (a + b) + c vs. a + (b + c) the result will be the same. Multiplication and addition only.

Up to this point, I've attempted to build a simple function that resolves whether the final value is equal to the compared equation value. What I would like is if I was able to compare both equations without their parenthesis. Thinking I need to look up regular expressions... but looking for a little help on direction.

let a = 1,
  b = 2,
  c = 3,
  number1 = (a * b) * c,
  number2 = a * (b * c);

function isAssociative(num1, num2) {
  let answer = num1 === num2;
  return `Are ${num1} and ${num2} associative... ${answer}`;
}

console.log(isAssociative(number1, number2));

Currently, this results in, 'Are 6 and 6 associative... true'. This is what I want, but if I changed the second argument to a static 6 when calling the function... then this is not an associative combo and I would like it to return false.

Upvotes: 2

Views: 491

Answers (2)

thielr7
thielr7

Reputation: 337

I found an answer I'm satisfied with.

let number1 = prompt('Enter an equation').toString().replace(/[^0-9,+,*]+/g,''),
  number2 = prompt('Enter equation 2').toString().replace(/[^0-9,+,*]+/g,'');

function isAssociative (num1, num2) {
  if (num1 === num2) {
    return eval(num1) === eval(num2);
  } else {
    return false;
  }
}

alert(isAssociative(number1, number2));

I could wait for the numbers to enter the function as a string, check for parenthesis first to verify it even qualifies... if parenthesis exist, then I could execute the regEx code and if they don't exist return 'not associative' at that point. For now, this works as well as I want it to.

Upvotes: 0

yunzen
yunzen

Reputation: 33439

You can use Mathjs and the simplify method:

console.clear();

term_a = 'a + ( b + c )'
term_b = '( a + b ) + c';

tree_a = math.simplify(term_a);
tree_b = math.simplify(term_b);

console.log(term_a, tree_a.equals(tree_b) ? 'equals' : 'differs from', term_b);

term_a = 'a + ( b + c + d )'
term_b = '( a + b ) + c';

tree_a = math.simplify(term_a);
tree_b = math.simplify(term_b);

console.log(term_a, tree_a.equals(tree_b) ? 'equals' : 'differs from', term_b);
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/5.4.2/math.min.js"></script>

Upvotes: 3

Related Questions