1到10之间的数字通过运算得到24

面试碰到的一道算法题,当时时间不够没做出来,现在整理了一下。
以下是暴力法的解,最简洁明了,最好理解

// 暴力法
 function get24(arr) {

    // 1 得到所有数字的排列
    const numsList = function dp(arr) {
      if (arr.length === 1) {
        return arr;
      }
      let r = [];
      for (let a = 0; a < arr.length; a++) {
        let arr1 = [...arr];
        let v = arr1[a];
        arr1.splice(a, 1);
        dp(arr1).forEach(e => {
          let t = []
          t = t.concat(e, v)
          r.push(t)
        })
      }
      return r;
    }(arr);

    // 2 得到运算符的全部情况
    const operators = function getOperators(operators, len) {
      let r = [];
      if (len === 1) {
        operators.forEach(e => {
          r.push([e])
        })
      } else {
        operators.forEach(e1 => {
          getOperators(operators, len - 1).forEach(e2 => {
            let b = [];
            b = b.concat(e1, e2);
            r.push(b)
          })
        })
      }
      return r;
    }(['+', '-', '*', '/'], 4);

    // 3 得到括号的全部情况
    const expression = [
      "`(${a} ${o1} ${b}) ${o2} ${c} ${o2} ${d}`",
      "`(${a} ${o1} ${b}) ${o2} (${c} ${o2} ${d})`",
      "`${a} ${o1} (${b} ${o2} ${c} ${o2} ${d})`",
      "`(${a} ${o1} ${b} ${o2} ${c}) ${o2} ${d}`",
      "`${a} ${o1} (${b} ${o2} ${c}) ${o2} ${d}`",
      "`(${a} ${o1} (${b} ${o2} ${c})) ${o2} ${d}`"
    ];

    for (let x = 0; x < numsList.length; x++) {
      let [a, b, c, d] = numsList[x];
      for (let y = 0; y < operators.length; y++) {
        let [o1, o2, o3] = operators[y];
        for (let z = 0; z < expression.length; z++) {
          let r1 = eval(expression[z]);
          let r = eval(r1)
          if (r === 24) {
            return r1
          }
        }
      }
    }
  }
let input = [1,2,3,4]
console.log(get24(input))

你可能感兴趣的:(算法)