我正在创建一个配对功能,在那里两个相同体重的球员将被配对.
它目前在相同重量的基础上工作.现在,我增加了另一个条件,球员有自己的水平.我的第一个条件是基于同样的体重.这起作用了.我的第二个条件是关于"班级",如果玩家有相同的班级,他们不应该被匹配/配对.
const source = [
{
entryID: 1,
entryName: "player1",
weight: 1900,
class: ['a', 'b'],
},
{
entryID: 2,
entryName: "player2",
weight: 1900,
class: ['a', 'b'],
},
{
entryID: 3,
entryName: "player3",
weight: 1900,
class: ['c', 'd'],
},
{
entryID: 4,
entryName: "player4",
weight: 1900,
class: ['c', 'd'],
},
];
console.log(combine(source))
function combine(data = [], different = 0, maxGroupSize = 2) {
const groups = [], related = [], sortedData = [...data].sort((a, b) => a.weight - b.weight),
alreadyInRela = (setX, eName) => {
let list = [...setX, eName]
return related.some(rela => list.every(l => rela.has(l)))
};
sortedData.forEach((el, indx) => {
let place = groups.findIndex( // find a place in a group forEach element, use indx as track
g => g.names.size < maxGroupSize // is the group incomplete ?
&& !g.names.has(el.entryName) // is entryName not in the group list (names Set) ?
&& (el.weight - g.weight) <= different
&& !alreadyInRela(g.names, el.entryName) // is (entryName + group list) does not already used ?
)
if (place < 0) { // not found -> create new group
let names = new Set().add(el.entryName) // create new group
groups.push({ names, indxs: [indx], weight: el.weight }) // group constitutive info
related.push(names) // keep track of group list
} else { // find a place in a group
groups[place].names.add(el.entryName) // related list is also updated
groups[place].indxs.push(indx) // add indx to retreive element in sortedData
}
});
return groups.reduce((r, g, i) => { // build result
if (g.indxs.length > 1) {
let key = `${i}_` + g.indxs.map(x => sortedData[x].weight).join('_')
r[key] = []
g.indxs.forEach(x => r[key].push(sortedData[x]))
}
return r
}, {})
}
我目前的输出:
{
0_1900_1900: [
{
class: ["a", "b"],
entryID: 1,
entryName: "player1",
weight: 1900
},
{
class: ["a", "b"],
entryID: 2,
entryName: "player2",
weight: 1900
}
],
1_1900_1900: [
{
class: ["c", "d"],
entryID: 3,
entryName: "player3",
weight: 1900
},
{
class: ["c", "d"],
entryID: 4,
entryName: "player4",
weight: 1900
}
]
}
目标输出(正如我们在这里看到的,具有相同职业的玩家没有连接/组合.这就是我需要瞄准的目标):
{
0_1900_1900: [
{
class: ["a", "b"],
entryID: 1,
entryName: "player1",
weight: 1900
},
{
class: ["c", "d"],
entryID: 3,
entryName: "player3",
weight: 1900
}
],
1_1900_1900: [
{
class: ["a", "b"],
entryID: 2,
entryName: "player2",
weight: 1900
},
{
class: ["c", "d"],
entryID: 4,
entryName: "player4",
weight: 1900
}
]
}