假设我有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
什么是最简单的算法方法来编写一个解决这个问题的程序?
假设我有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
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.
}
当您提到“唯一数字”时,假设您指的是使用手头所有数字生成的可能结果宇宙中的结果。
如果是这样,为什么不先尝试对所有运算符和可用数字进行排列组合呢?
如果您想确保从这些数字中生成唯一的数字,并且没有机会从不同的数字集合中获得相同的数字,则应使用基数算术,类似于十进制、十六进制等。
但是您需要知道数字的最大值。
基本上,它将是 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