I'm take a 2d array that looks something like [[player1, 10], [player2, 8]]
but with around 12 players. I'm satisfied enough with the sorting I have hear, except with this method teamA always gets the "first pick" of the better player. I am struggling to figure out a way to give teamB the better player every other time. below is the code as is that works "well enough".
data = [["player1", 10]. ["player2", 8], ["player3", 7], ["player4", 9]];
var teamA = [];
var teamB = [];
var remaining = [];
for (item in data) {
remaining.push(data[item].slice());
}
for (i in data) {
var max = 0;
var selection = [,];
var index = -1;
for (k in remaining) {
if (remaining[k][1] > max) {
selection = remaining[k];
max = remaining[k][1];
index = k;
}
}
remaining.splice(index, 1);
if (i % 2 == 0) {
teamA.push(selection);
} else {
teamB.push(selection);
}
}
This results in teamA: [["player1, 10],["player2", 8]]
and teamB: [["player4", 9],["player3", 7]]
What I would prefer is player2 and player3 switch teams. Here's what I tried.
// inside my first for loop
if (3 % i == 0) {
i++;
} else if (4 % i == 0) {
i--;
}
In my brain, this should have worked just fine but wow did it not! I ended up with like 9 players on teamB and 3 on teamA. I fiddled with different variations of this approach with no luck.
Any pointers?
EDIT: For clarification, it can be assumed the data set will be unsorted coming in, and that the length of the data set will always be even. There won't be a team with more players than the other.