java - 我如何编写大量的 for 循环

标签 java python algorithm math loops

我是编程新手,所以如果我没有正确地问这个问题,我很抱歉在措辞上。

我有以下代码:

int sum = 100;
int a1 = 20;
int a2 = 5;
int a3 = 10;
for (int i = 0; i * a1 <= sum; i++) {
    for (int j = 0; i * a1 + j * a2 <= sum; j++) {
        for (int k = 0; i * a1 + j * a2 + k * a3 <= sum; k++) {
            if (i * a1 + j * a2 + k * a3 == sum) {
                System.out.println(i + "," + j + "," + k);
            }
        }
    }   
}

基本上它所做的是告诉我 a1a2a3 的不同组合等于上面的总和(在本例中100).这工作正常,但我现在正在尝试将它应用于更大的数据集,我不确定如果不手动编程 for 循环或提前知道我将拥有多少变量(可能是 10 到 6000 ).我基本上有一个从数组加载数据的 sql 查询。

有没有一种方法可以在 Java 或 python(我正在学习两者)中自动创建嵌套的 forif 循环?

提前致谢。

最佳答案

递归。

这听起来像是您要解决的问题:

your current example: 20x1 + 5x2 + 10x3 = 100

so in general you are doing: A1x1 + A2x2 + ... + Anxn = SUM

so you pass in an array of constants {A1, A2, ..., An} and you want to solve for {x1, x2, ..., xn}

    public void findVariables(int[] constants, int sum, 
                              int[] variables, int n, int result) {
        if (n == constants.length) { //your end condition for the recursion
            if (result == sum) {
                printArrayAsList(variables);
            }
        } else if (result <= sum){ //keep going
            for (int i = 0; result + constants[n]*i <= sum; i++) {
                variables[n] = i;
                findVariables(constants, sum, variables, n+1, result+constants[n]*i);
            }
        }
    }

并调用您将使用的示例:

    findVariables(new int[] {20, 5, 20}, 100, new int[] {0,0,0}, 0, 0)

关于java - 我如何编写大量的 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6240770/

相关文章:

java - while循环只执行一次

java - 将ArrayList插入MySQL

python - 如何在 Tkinter 中创建淡出效果?我的代码崩溃

python - 如何从 C 创建一个 numpy 记录数组

python - 在 python : how to split newlines while ignoring newline inside quotes 中解析字符串

python - 用通配符匹配 2 个列表的算法

Javafx ListView 上下文菜单

java - 删除 Casper 数据集中的默认排序依据

python - 如何打印与最小残差关联的值 - Python

algorithm - 计算对象在二叉树中的出现次数