我有一个对象数组,它们具有如下所示的键值对。
pyre_company = db.child("companies/data").order_by_child("id").equal_to(company_id).limit_to_first(1).get()
for company in pyre_company.each():
print(company.val()) // {'id': 427, 'name': 'Bugbear Entertainment', 'type': 'developer'}
我想要实现的是自动选择15名球员,其中守门员应该是2名,5名后卫,5名中场球员和3名前锋,来自700名球员的阵容,这样他们的总值接近或等于100。任何帮助将不胜感激: - )
答案 0 :(得分:1)
首先将玩家分成他们的位置:
const getPosition = (arr, pos) => arr.filter(({position}) => position === pos);
然后使用一种方法将这些数组组合成一个具有指定长度的数组,该数组可以检验所有组合:
function combinations(arr, length) {
function* walk(start, depth) {
for(let i = start; i < arr.length; i++) {
if(depth) {
for(const combo of walk(i + 1, depth - 1)) {
yield [...combo, arr[i]];
}
} else {
yield [arr[i]];
}
}
}
return walk(0, length);
}
现在要获得所有不同的团队,我们可以将它们组合起来:
function* compose(iterator, ...iterators) {
for(const value of iterator) {
if(iterators.length) {
for(const combo of compose(...iterators)) {
yield [value, ...combo];
}
} else {
yield [value];
}
}
}
const teams = compose(
combinations(getPosition("Goalkeeper"), 3),
combinations(getPosition("Defender"), 5),
combinations(getPosition("Midfielder"), 5),
combinations(getPosition("Forward"), 3)
);
现在我们必须找到最好的团队:
const distance = team => Math.abs(team.reduce((score, player) => score + player.value, 0) - 100);
let best = teams.next().value;
for(const team of teams) {
if(distance(best) > distance(team))
best = team;
if(!distance(best)) break;
}