My 24 game solution found answers that weren't in the tests

What is your hint or solution suggestion?
Hi everyone! I found a solution to the 24 game question. It failed the tests, but the answers it came up with were actually valid. Below is my code. Comments are welcome. How could I improve the answer?

function permutationsOf(arr) {
  if (arr.length == 1) {
    return [arr];
  } else {
    let result = []
    for (let i=0; i<arr.length; i++) {
      let rest = arr.slice(0,i).concat(arr.slice(i+1));
      let restPermutations = permutationsOf(rest)
      for (let j=0; j<restPermutations.length; j++) {
        result.push([arr[i]].concat(restPermutations[j]));
      }
    }
    return result;
  }
}

function combinationsOf(arr) {
  let result = []
  for (let i=0; i<arr.length; i++) {
    for (let j=0; j<arr.length; j++) {
      for (let k=0; k<arr.length; k++) {
        result.push([arr[i],arr[j],arr[k]]);

      }
    }
  }
  return result;
}

function pPatterns(a, b, c, d, o, p, q) {
  let ps = [
    `${a}${o}${b}${p}${c}${q}${d}`,
    `(${a}${o}${b}${p}${c})${q}${d}`,
    `${a}${o}(${b}${p}${c}${q}${d})`,
    `((${a}${o}${b})${p}${c})${q}${d}`,
    `(${a}${o}(${b}${p}${c}))${q}${d}`,
    `${a}${o}((${b}${p}${c})${q}${d})`,
    `${a}${o}(${b}${p}(${c}${q}${d}))`,
    `(${a}${o}${b})${p}(${c}${q}${d})`,
    `${a}${o}(${b}${p}${c})${q}${d}`,
    `(${a}${o}${b})${p}${c}${q}${d}`,
    `${a}${o}${b}${p}(${c}${q}${d})`];
    return ps
}

//console.log(pPatterns('1','2','3','4', '-','+','*'))


//console.log(permutationsOf([1,2,3,4]).length)
//console.log(combinationsOf([1,2,3,4]).length)

function solve24 (numStr) {

  let per = permutationsOf(numStr.split(''));
  let os = combinationsOf(['+','-','/','*']);
  for (let i=0; i<per.length; i++){
    for (let j=0; j<os.length; j++){
      let expressions = pPatterns(...per[i].concat(os[j]));
      for (let k=0; k<expressions.length; k++) {
        if (eval(expressions[k]) == 24) {
          return expressions[k];
        }
      }
    }
  }

}

console.log(solve24(“4123”));

Challenge: 24 game

Link to the challenge:

From the description of the task I don’t see that "6*(8/(9-7))" should be invalid, so I’d say that tests should be updated.

You can contribute here: freeCodeCamp/24-game.md at main · freeCodeCamp/freeCodeCamp · GitHub

My favorite novel answer was:
4/((1/2)/3)

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