如何优化编码数字游戏?

How to optimize coding numbers game?

我想用给定的 6 个以上的输入构造一个数字。

例如,如果我想使用输入 [2,4,5,10,30,50,66][=29= 实现数字 280 ] 我希望它成为 return 这样的字符串:((2+5) * 4 * 10)。每个解决方案我只能使用一次输入数字。我写了一个基本上可以做到的代码;

1- 存储给定输入的所有可能子集。

2-生成算子所有可能的排列(根据子集长度它们的长度是changed.So可以组成一个有效的表达式)

3- 然后用有效的运算符排列连接子集。然后用堆算法再次排列。

4-将表达式转换为Reverse Polish Notation并进行计算。如果等于 target 则 return.

我的主要代码如下

for (let i = 0; i < inputSubsets.length; i++) {
  const operatorPermutations = getPermutations(
    operators,
    inputSubsets[i].length - 1
  )
  let filteredOperators = []

  let sum = inputSubsets[i].reduce((a, b) => a + b, 0)

  if (sum < target) {
    filteredOperators = operatorPermutations.filter((perm) => {
      return perm.includes("*")
    })
  } else {
    filteredOperators = operatorPermutations
  }

  for (let j = 0; j < filteredOperators.length; j++) {
    let expression = inputSubsets[i].concat(filteredOperators[j])

    if (permutationHeap(expression, "", target)) {
      const t1 = performance.now()
      console.log(postfixToInfix(validExpression.join(" ")))

      console.log(`Operation lasted : ${(t1 - t0) / 1000} seconds`)
      return true
    }
  }
}

如果子集的总和低于 target.Which,我将省略不包含“*”的排列,将计算时间从 155 秒减少到 20-22 秒。我想知道我可以做些什么来减少时间。

首先,您可以从输入数组中取出两个数字,然后对它们应用随机操作,例如

const plus = ( (a, b) => a + b);
const result1 = plus(inputs[0], inputs[1]);
if(result1 == 280){ console.log("I win!"); }

然后尝试另一个,比如

const times = ( (a, b) => a * b);
const result2 = times(result1, inputs[2]);

...等等。最终有了足够的处理能力,你会强行通过所有组合。

我绝对不是说这是最聪明的方法,但如果你真的只是在寻找一个起点,那么这应该有助于让脑汁流动起来。