【发布时间】:2022-01-01 16:31:00
【问题描述】:
目前正在编写一个程序,用于查找数组中 3 个给定数字的最佳比例。然而,我目前的代码只需要 3 个数字并安排它们以找到最接近 100 的 3 个数字排列。我需要代码具有适应性,以便它采用 3 个数字并给出最接近 100 的 n 数字排列。
public static int[] mmru(int[] array) {
int result = 1000;
int[] ideal = new int[0];
int closestResult = 100;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
result = 100 - array[i] - array[j] - array[k];
if (result == 0) {
ideal = new int[]{array[i], array[j], array[k]};
return ideal;
} else {
if (result < closestResult && result > 0) {
ideal = new int[]{array[i], array[j], array[k]};
closestResult = result;
}
}
}
}
}
return ideal;
}
我现在的解决方案是手动添加更多 for 循环和数组元素。
示例 - 一个由 3 个数字组成的数组,使用 3 个数字输出 8 个数字的排列以最接近 100。例如。 [8,13,15] 给出 [8,8,13,13,13,15,15,15] 的输出
public static int[] mmrh8(int[] array) {
int result = 1000;
int[] ideal = new int[0];
int closestResult = 100;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
for (int k = 0; k < 3; k++) {
for (int l = 0; l < 3; l++) {
for (int m = 0; m < 3; m++) {
for (int n = 0; n < 3; n++) {
for (int o = 0; o < 3; o++) {
for (int p = 0; p < 3; p++) {
result = 100 - array[i] - array[j] - array[k] - array[l] - array[m] - array[n] - array[o] - array[p];
if (result == 0) {
ideal = new int[]{array[i], array[j], array[k], array[l], array[m], array[n], array[o], array[p]};
return ideal;
} else {
if (result < closestResult && result > 0) {
ideal = new int[]{array[i], array[j], array[k], array[l], array[m], array[n], array[o], array[p]};
closestResult = result;
}
}
}
}
}
}
}
}
}
}
return ideal;
}
有没有办法让for循环和数组元素的数量可变?
任何帮助表示感谢!
【问题讨论】:
-
我希望这是一个XY Problem 类型的问题。
标签: java loops for-loop recursion iteration