Today I have solved the problem in javascript

 The 24 game is played as follows. You are given a list of four integers, each between 1 and 9, in a fixed order. By placing the operators +, -, *, and / between the numbers, and grouping them with parentheses, determine whether it is possible to reach the value 24.

For example, given the input [5, 2, 7, 8], you should return True, since (5 * 2 - 7) * 8 = 24.

Write a function that plays the 24 game.

const nums = [5, 2, 7, 8];


function judgePoint24(nums) {

  const EPSILON = 1e-6;

  const TARGET = 24;


  const dfs = (arr) => {

    if (arr.length === 1) {

      return Math.abs(arr[0] - TARGET) < EPSILON;

    }


    for (let i = 0; i < arr.length; i++) {

      for (let j = 0; j < arr.length; j++) {

        if (i !== j) {

          const next = [];

          for (let k = 0; k < arr.length; k++) {

            if (k !== i && k !== j) {

              next.push(arr[k]);

            }

          }


          for (let k = 0; k < 4; k++) {

            if (k < 2 && j > i) continue; 


            if (k === 0) next.push(arr[i] + arr[j]);

            else if (k === 1) next.push(arr[i] * arr[j]);

            else if (k === 2) next.push(arr[i] - arr[j]);

            else {

              if (Math.abs(arr[j]) > EPSILON) {

                next.push(arr[i] / arr[j]);

              } else {

                continue;

              }

            }


            if (dfs(next)) {

              return true;

            }


            next.pop(); 

          }

        }

      }

    }

return false;

  };

return dfs(nums);

}

console.log(judgePoint24(nums));

Output:

true



Comments

Popular posts from this blog

Building a Full-Stack Student Management System with React.js and NestJS

Today I have solved the problem in javascript

Today I have solved problem in javascript