标签:嵌套 null 算法思路 tuple sum 组合 sys 整数 image
有4个砝码,总重量是40克,砝码的质量是整数,且个不相等.请确定他们的质量,使之能称出1-40克任何整数质量的物体.
注意: 要理清楚嵌套关系
再从1-40逐个进行试探
Python
# 产生一组 (a,b,c,d)
# 然后在1-40中去试探,可以的话就是了
def fn():
# 首先a+b+c+d=40,且各不相等
# 根据等式就可以减少一重循环
for a in range(1, 41):
for b in range(1, 41):
for c in range(1, 41):
# d由等式得到
d = 40 - a - b - c
num_tuple = (a, b, c, d)
if judge(num_tuple):
return num_tuple
def judge(num_tuple):
for x in range(1, 41):
if not find_result(x, num_tuple):
break
else:
return True
return False
def find_result(num, num_tuple):
for x1 in [-1, 0, 1]:
for x2 in [-1, 0, 1]:
for x3 in [-1, 0, 1]:
for x4 in [-1, 0, 1]:
result = (x1 * num_tuple[0] + x2 * num_tuple[1] + x3 * num_tuple[2] + x4 * num_tuple[3])
# 相等就说明找到了
if result == num:
return True
return False
print(fn())
Java
import java.util.Arrays;
public class 天平称物 {
static int[] operator_arr;
static void init() {
operator_arr = new int[] { -1, 0, 1 };
}
static int[] fn() {
int[] result = null;
for (int a = 1; a <= 40; a++) {
for (int b = 1; b <= 40; b++) {
for (int c = 1; c <= 40; c++) {
for (int d = 1; d <= 40; d++) {
result = new int[] { a, b, c, d };
if (judge(result)) {
return result;
}
}
}
}
}
return new int[] {};
}
static boolean judge(int[] result) {
for (int w = 1; w <= 40; w++) {
if (!find_result(result, w)) {
return false;
}
}
return true;
}
static boolean find_result(int[] result, int weight) {
for (int x1 : operator_arr) {
for (int x2 : operator_arr) {
for (int x3 : operator_arr) {
for (int x4 : operator_arr) {
int sum_num = x1 * result[0] + x2 * result[1] + x3 * result[2] + x4 * result[3];
if (sum_num == weight) {
return true;
}
}
}
}
}
return false;
}
public static void main(String[] args) {
init();
System.out.println(Arrays.toString(fn()));
}
}
标签:嵌套 null 算法思路 tuple sum 组合 sys 整数 image
原文地址:https://www.cnblogs.com/Rowry/p/11870350.html