【问题标题】:Find a math algorithm for an equation查找方程的数学算法
【发布时间】:2015-05-25 03:35:29
【问题描述】:

我只是在 math.stackexchange 上发布了一个数学问题,但我会在这里向人们询问一种编程递归算法。

问题:从1到9填空数字(每个空格一次且仅一次)以完成方程式。

附加条件:

1. Mathematic priority DOES matter. 
2. All numbers (include evaluation result) should be integers.
Which mean the divide should be divisible (E.g. 9 mod 3 = 0 is OK, 8 mod 3 != 0 is not OK).
3. For those who don't know (as one in the original question), the operations in the diagram are: 
+ = plus; : = divide; X = multiple; - = minus.

应该有超过 1 个答案。我想要一个递归算法来找出所有的解决方案。

Original question

PS:我想了解递归算法,性能提升。我试图使用蛮力解决问题。我的电脑冻结了很长一段时间。

【问题讨论】:

  • 到目前为止你有什么,你到底在问什么?我希望不是“你能帮我写代码吗?”
  • 我只有一个蛮力解决方案。我正在寻找一种快速、易于阅读和开发的算法。我曾想过使用递归,但不知道从哪里开始,从哪里结束,从哪里分支循环。
  • “我试图用蛮力解决这个问题。我的电脑卡了好一阵子。” 奇怪,只有 9 个! = 362,800 种不同的可能性,所以暴力破解应该很快。
  • 也许我使用了太多的循环、变量、分支条件?
  • @Eddie 可能有太多循环,请发布您的蛮力解决方案。

标签: algorithm math recursion


【解决方案1】:

你必须找到正确的排列方式

9! = 362880

这不是一个大数字,您可以通过以下方式进行计算:

isValid(elements)
    //return true if and only if the permutation of elements yields the expected result
end isValid

isValid 是验证器,它检查给定的排列是否正确。

calculate(elements, depth)
    //End sign
    if (depth >= 9) then
        //if valid, then store
        if (isValid(elements)) then
            store(elements)
        end if
        return
    end if
    //iterate elements
    for element = 1 to 9
        //exclude elements already in the set
        if (not contains(elements, element)) then
            calculate(union(elements, element), depth + 1)
        end if
    end for
end calculate

拨打calculate如下:

calculate(emptySet, 1)

【讨论】:

  • 您从哪里获得四个插槽?我看到了九个。
  • 我也是,我也看到了 9。但是算法看起来不错。我明天试试。
  • 深度确保它是四个插槽。当 depth >= 4 时,算法将因返回而停止。每次迭代都会增加深度,其初始值为1。所以它是第一个插槽,第二个插槽,第三个插槽,第四个插槽,如果需要存储并停止。这就是简单的想法。
  • 是的,我明白了。只是它不像原始问题那样适合 9 个插槽,但这就是适合您的算法。还是谢谢你。
  • 如果我没记错的话,你必须在4个地方尝试9个数字,对吧?
【解决方案2】:

这是使用 PARI/GP 的解决方案:

div(a,b)=if(b&&a%b==0,a/b,error())
f(v)=
{
  iferr(
    v[1]+div(13*v[2],v[3])+v[4]+12*v[5]-v[6]-11+div(v[7]*v[8],v[9])-10==66
  , E, 0)
}
for(i=0,9!-1,if(f(t=numtoperm(9,i)),print(t)))

函数f 在这里定义了特定的函数。我使用了一个辅助函数 div,如果除法失败(产生非整数或除以 0)会引发错误。

通过拆分涉及除法的块并在它们失败时提前中止,可以提高程序的效率。但是因为这只需要几毫秒就可以通过所有 9!排列组合我认为不值得。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-04
    • 1970-01-01
    • 2015-10-06
    • 1970-01-01
    • 2016-11-03
    • 2018-08-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多