从给定数字计算唯一值

时间:2012-12-31 15:07:37

标签: algorithm

假设我有6个随机数,我想从这些数字中计算出一些独特的值。

修改 允许的操作是+, - ,*和/。每个号码只能使用一次。你不必使用所有数字。

示例:

Given numbers: 3, 6, 100, 50, 25, 75
Requested result: 953

3 + 6 = 9
9 * 100 = 900
900 + 50 = 950
75 / 25 = 3
3 + 950 = 953

编写解决此问题的程序的最简单算法方法是什么?

5 个答案:

答案 0 :(得分:4)

最简单的方法是尝试所有这些:您有六个数字,这意味着最多可以放置五个位置,您可以放置​​一个运算符,最多可以6!个排列。鉴于只有四个运营商,您需要经历6!*4^5或737280种可能性。这可以通过递归函数轻松完成,甚至可以使用嵌套循环。根据语言的不同,您可以使用库函数来处理排列。

与语言无关的递归方法可以定义三个函数:

int calc(int nums[6], int ops[5], int countNums) {
    // Calculate the results for a given sequence of numbers
    // with the specified operators.
    // nums are your numbers; only countNums need to be used
    // ops are your operators; only countNums-1 need to be used
    // countNums is the number of items to use; it must be from 1 to 6
}

void permutations(int nums[6], int perm[6], int pos) {
    // Produces all permutations of the original numbers
    // nums are the original numbers
    // perm, 0 through pos, is the indexes of nums used in the permutation so far
    // pos, is the number of perm items filled so far
}

void solveRecursive(int numPerm[6], int permLen, int ops[5], int pos) {
    // Tries all combinations of operations on the given permutation.
    // numPermis the permutation of the original numbers
    // permLen is the number of items used in the permutation
    // ops 0 through pos are operators to be placed between elements
    // of the permutation
    // pos is the number of operators provided so far.
}

答案 1 :(得分:4)

我认为最简单的算法方法是backtracking。它实现起来相当容易,如果存在,总会找到解决方案。基本思想是递归的:在构建解决方案的每一步做出任意选择,然后从那里开始。如果不能解决问题,请尝试其他选择。当您没有选择时,向前一个选择点报告失败(或者如果没有先前的选择点,则报告无法找到解决方案)。

您的选择是:涉及多少个数字,每个数字是什么(选择每个数字位置),以及操作员如何连接(每个操作员位置的选择)。

答案 2 :(得分:1)

当您提及“唯一数字”时,假设您的意思是使用手头的所有数字生成的结果的可能范围内的结果。

如果是这样,为什么不试一下所有运算符和可用数字的排列?

答案 3 :(得分:1)

如果您想保证从这些数字中生成一个唯一的数字,而不能从不同的数字集中获得相同的数字,那么您应该使用基数算术,类似于十进制,十六进制等。

但你需要知道数字的最大值。

基本上,它是A + B * MAX_A + C * MAX_A * MAX_B + D * MAX_A * MAX_B * MAX_C + E * MAX_A * MAX_B * MAX_C * MAX_D + F * MAX_A * ... * MAX_E

答案 4 :(得分:0)

使用递归来置换数字和运算符。它是O(6!* 4 ^ 5)

相关问题