【发布时间】:2017-09-30 02:26:32
【问题描述】:
假设我有一个包含 N(对于本例 N=10)个值的数组,每个值都在 1-10 之间:
10
8.4
7.9
7.8
7.7
7.3
7.3
6.9
6.1
5.8
现在,我想将它们分成 P 个组(对于本例 P=2),所有组将是偶数(也就是它们的 SUM),或者尽可能接近。
我已经为此写了一个算法:
public static void mainLogic(ArrayList<Player> team) {
Player currentPlayer = new Player();
Player minDifPlayer = new Player();
double minDiff = 100;
for (int ind = 0; ind < team.size(); ind++) {
if (team.isEmpty())
return;
double temp = team.get(ind).get_playeroverall();
if (ind == team.size() - 1) {
//if num of Player match for two teams
if (team.size() < 18) {
// if the teams are equals or teamA AVG small then teamB
if (sum(teamA) <= sum(teamB)) {
teamA.add(currentPlayer);
teamB.add(minDifPlayer);
Results.TempArray.add(currentPlayer);
Results.TempArray.add(minDifPlayer);
team.remove(currentPlayer);
team.remove(minDifPlayer);
//if teamB AVG small then teamA
} else if (sum(teamA) > sum(teamB)) {
teamB.add(currentPlayer);
teamA.add(minDifPlayer);
Results.TempArray.add(currentPlayer);
Results.TempArray.add(minDifPlayer);
team.remove(currentPlayer);
team.remove(minDifPlayer);
}
// if the teams are full, Player are subscribed to the following team
if (teamA.size() == 6 && teamB.size() == 6) {
teamC.addAll(team);
Results.TempArray.addAll(team);
team.clear();
}
ind = 0;
minDiff = 100;
if (!team.isEmpty())
temp = team.get(ind).get_playeroverall();
}
}
for (int pointer = ind + 1; pointer <= team.size() - 1; pointer++) {
double rankToCompare = team.get(pointer).get_playeroverall();
if (Math.abs(temp - rankToCompare) < minDiff) {
minDiff = Math.abs(temp - rankToCompare);
currentPlayer = team.get(ind);
minDifPlayer = team.get(pointer);
}
}
}
}
问题在于算法没有完美运行。对于上面他给我的同一个例子
10 8.4
7.8 7.9
7.3 7.3
6.9 7.7
5.8 6.1
SUM=37.8 SUM=37.4
我可以通过这种方式更好地手动匹配它们:
10 8.4
7.7 7.9
7.3 7.3
6.9 7.8
5.8 6.1
SUM=37.7 SUM=37.5
(我写的算法针对 3 组,每组 6 名玩家 - 意味着 18 名玩家顶部,当额外的玩家移动到下一组时)
【问题讨论】: