Possible solution

What is your hint or solution suggestion?

Summary

Challenge: 24 game

function solve24 (numStr) {

  let arr = Array.from(numStr, Number);

  let tmp;

  let validExp = false;

  // Function to swap variables' content.

  function swap(index1, index2) {

    tmp = arr[index1];

    arr[index1] = arr[index2];

    arr[index2] = tmp;

  }

  // Generate arrays of permutations using the algorithm.

  const validateMathExpression = (arr) => {

   const [a,b,c,d] = arr

   if( (a*b*c*d) === 24 ) return `${a}*${b}*${c}*${d}`;

   else if( a+b+c+d === 24 ) return  `${a}+${b}+${c}+${d}`;

   else if( a-b+c+d === 24 ) return `${a}-${b}+${c}+${d}`;

   else if( a+b-c+d === 24 ) return `${a}+${b}-${c}+${d}`;

   else if( a+b+c-d === 24 ) return `${a}+${b}+${c}-${d}`;

   else if( (a*b)/(c-d) === 24 ) return `(${a}*${b})/(${c}-${d})`;

   else if( (a-b/c)*d === 24 ) return `(${a}-${b}/${c})*${d}`;

   else if( (a+b)*(c+d) === 24 ) return `(${a}+${b})*(${c}+${d})`;

  }

  function generate(int) {

    if (int === 1 && !validExp) {

      validExp =  validateMathExpression(arr)

    } else {

      for (let i = 0; i != int; ++i) {

        generate(int - 1);

        swap(int % 2 ? 0 : i, int - 1);

      }

    }

  }

generate(arr.length)

return validExp? validExp : "no solution exists"

}

Link to the challenge:

Hello there.

Thank you, for your contribution. For future contributions, please wrap your solution within :

[details]
```
code goes here...
```
[/details]

Also, when you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor ( </> ) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.