Back to Freecodecamp

Challenge 237: Equation Validation

curriculum/challenges/english/blocks/daily-coding-challenges-javascript/69b559d2903b9e4afe9075f7.md

latest2.6 KB
Original Source

--description--

Given a string representing a math equation, determine whether it is correct.

  • The left side may contain up to three positive integers and the operators +, -, *, and /.
  • The equation will be given in the format: "number operator number = number" (with two or three numbers on the left). For example: "2 + 2 = 4" or "2 + 3 - 1 = 4".
  • The right side will always be a single integer.

Follow standard order of operations: multiplication and division are evaluated before addition and subtraction, from left-to-right.

--hints--

isValidEquation("2 + 2 = 4") should return true.

js
assert.isTrue(isValidEquation("2 + 2 = 4"));

isValidEquation("2 + 3 - 1 = 4") should return true.

js
assert.isTrue(isValidEquation("2 + 3 - 1 = 4"));

isValidEquation("8 / 2 = 4") should return true.

js
assert.isTrue(isValidEquation("8 / 2 = 4"));

isValidEquation("10 * 5 = 50") should return true.

js
assert.isTrue(isValidEquation("10 * 5 = 50"));

isValidEquation("2 - 2 = 0") should return true.

js
assert.isTrue(isValidEquation("2 - 2 = 0"));

isValidEquation("2 + 9 / 3 = 5") should return true.

js
assert.isTrue(isValidEquation("2 + 9 / 3 = 5"));

isValidEquation("20 - 2 * 3 = 14") should return true.

js
assert.isTrue(isValidEquation("20 - 2 * 3 = 14"));

isValidEquation("2 + 5 = 6") should return false.

js
assert.isFalse(isValidEquation("2 + 5 = 6"));

isValidEquation("10 - 2 * 3 = 24") should return false.

js
assert.isFalse(isValidEquation("10 - 2 * 3 = 24"));

isValidEquation("3 + 9 / 3 = 4") should return false.

js
assert.isFalse(isValidEquation("3 + 9 / 3 = 4"));

--seed--

--seed-contents--

js
function isValidEquation(equation) {

  return equation;
}

--solutions--

js
function isValidEquation(equation) {
  const [left, right] = equation.split(" = ");
  const tokens = left.split(" ");

  for (let i = 1; i < tokens.length - 1; i += 2) {
    const operator = tokens[i];
    if (operator === "*" || operator === "/") {
      const leftOperand = Number(tokens[i - 1]);
      const rightOperand = Number(tokens[i + 1]);
      const computed = operator === "*" ? leftOperand * rightOperand : leftOperand / rightOperand;
      tokens.splice(i - 1, 3, String(computed));
      i -= 2;
    }
  }

  let result = Number(tokens[0]);
  for (let i = 1; i < tokens.length - 1; i += 2) {
    const operator = tokens[i];
    const operand = Number(tokens[i + 1]);
    result = operator === "+" ? result + operand : result - operand;
  }

  return result === Number(right);
}