带列表的Java中的嵌套循环的动态数

时间:2018-11-04 04:18:38

标签: java loops recursion

我已经用Java创建了一个函数来查找列表的所有可能组合。我仅为2个技能创建了此代码,但是由于技能数量可能会动态变化,因此我需要更改代码以支持动态数量的嵌套循环,以找到技能专家的组合。

public List<ProjectAndTeam> teamCombinations(List<ProjectAndTeam> projectAndTeams) {
    List<ProjectAndTeam> allTeamCombinations = new ArrayList<>();
    for (ProjectAndTeam currentProjectTeam : projectAndTeams) {
        ProjectAndTeam projectAndTeam = new ProjectAndTeam();
        projectAndTeam.project = currentProjectTeam.project;
        for (int i = 0; i < currentProjectTeam.expertForSkill.get(0).expertList.size(); i++) {
            for (int j = 0; j < currentProjectTeam.expertForSkill.get(1).expertList.size(); j++) {
                ExpertForSkill expertForSkill = new ExpertForSkill();
                expertForSkill.skill = currentProjectTeam.expertForSkill.get(0).skill;
                expertForSkill.expertList.add(currentProjectTeam.expertForSkill.get(0).expertList.get(i));
                ExpertForSkill expertForSkillSecond = new ExpertForSkill();
                expertForSkillSecond.skill = currentProjectTeam.expertForSkill.get(1).skill;
                expertForSkill.expertList.add(currentProjectTeam.expertForSkill.get(1).expertList.get(j));
                projectAndTeam.expertForSkill.add(expertForSkill);
                projectAndTeam.expertForSkill.add(expertForSkillSecond);
            }
        }
        allTeamCombinations.add(projectAndTeam);
    }
    return allTeamCombinations;
}

这是我的ProjectAndTeam,ExprtForSkill和Expert类

public class ProjectAndTeam {
int id;
Project project;
List<ExpertForSkill> expertForSkill = new ArrayList<>();
double totalSalary;
double totalProductivity;
}

public class ExpertForSkill {
String skill;
List<Expert> expertList = new ArrayList<>();
}

public class Expert {
int id;
List<String> skills = new ArrayList<>();
int capacity;
double productivity;
double salary;
}

如何获得具有不同数量嵌套循环的所有组合?

我相信我必须编写一个递归函数来处理它,但是我很困惑。

1 个答案:

答案 0 :(得分:1)

我将不使用递归,而是通过单个循环和代表ijk等的计数器数组来实现您的*动态嵌套循环”。您将始终递增最后一个可能的计数器(代表最里面的循环),直到到达末尾为止,在这种情况下,您将对其进行重置,将其外部的循环递增1,然后继续。

假设您有n种不同的技能。簿记可能看起来像这样:

int[] counters = new int[n]; // i, j, k, ...

while(counters[0] < currentProjectTeam.expertForSkill.get(0).expertList.size()) {
    // Compute projectAndTeam, using loop over counters
    allTeamCombinations.add(projectAndTeam);

    for(int currentDepth = n - 1; ++counters[currentDepth] == currentProjectTeam.expertForSkill.get(currentDepth).expertList.size() && currentDepth > 0; currentDepth--) {
        counters[currentDepth] = 0;
    }
}

您可能应该为counters中每个项目对应的技能值提供一个数组,并在该最终循环中对其进行更新。这可能比重新计算计算projectAndTeam的循环中的所有内容更容易。