生成所有总和组合
给定一组 6 个数字(例如 1,5,8,9,2,6)和 2 个操作数(例如 + 和 -),我想知道如何生成所有可能的有效和,例如 1+8=9 等等。
数字可以是正数 0-9,操作数可以是 +-/* 平方和平方根
如果有人可以提供帮助,我将非常感激。
谢谢
Given a set of 6 numbers e.g 1,5,8,9,2,6 and 2 operands e.g + and - i was wondering how you would go about generating all possible valid sums e.g 1+8=9 and so on.
The numbers could be an positive number 0-9 and the operands could be +-/* squared and Square Root
If any one can help i would really appreciate it.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为它是一个集合,并且数字的范围是 [0,9] - 一个简单的解决方案将是回溯,需要 3^n <最多 3^10 次迭代。只需迭代所有可能性(每个元素可以在列表中/在列表外,以及两个元素之间“连接”的所有可能性。对于一元操作:使用它/不使用它)。
伪代码:
注意 - 您可能需要对一元运算进行额外处理,但它不会对算法产生太大影响。
since it is a set, and the range of numbers is [0,9] - a trivial solution will be backtracking, requiring 3^n < 3^10 iterations at most. just iterate over all possibilities (each element can be in/out of the list, and all possibilities to 'connect' between two elements. for unary oparations: with it/ with out it).
pseudo code:
note - you might need an extra handling for the unary operations, but it will not change the algorithm much.
“正数0-9”
0 不是正数。
“操作数可以是 +-/* 平方和平方根”
平方和平方根只采用一个参数,那么如何将其应用于列表的两个元素呢?
由于您没有在此处指定任何语言,因此您的帖子中所述的添加解决方案如下:
这允许相同元素与其自身求和,如果不希望出现此行为,请相应地更改它。
根据需要使用其他运算符。
C 语言中非常详细的示例:
"positive number 0-9"
0 is not a positive number.
"the operands could be +-/* squared and Square Root"
The square and the square root do only take one parameter, so how do you apply this over two elements of your list?
As you didn't specify any language here the solution for the addition as stated in your post:
This allows sums of the same element with itself, if this behaviour is not intended, change it accordingly.
Use other operators as needed.
Very verbose example in C:
好吧,由于只有 6*5*4(从集合中选取数字)*4(操作数),因此您可以轻松生成所有可能的排列并检查每个排列的有效性。我无法在 Objective C 中提供代码,但您可以使用嵌套循环来获取所有可能的排列,执行计算并打印排列(如果计算结果与您在排列中选择作为“结果”的数字匹配)
well, since there are only 6*5*4 (picking numbers from the set) *4 (operands), you could easily generate all possible permutations and check each for validity. I cannot provide code in objective c, but you could just use nested loops to get all possible permutations, perform the computation and print the permutation if the result of the computation matches the number you picked as "result" in the permutation