John Davidson

How do I make 2 teams of equal size and skill level given an array of 20 players with varying skills - and make it scalable in PHP

0 comments
Message:


This was asked to be solved in PHP, but the concepts from any language would do.


This was asked to be scalable i.e. you can add players after, and your algo would still work.


You're given 20 total players (more can be added). Each is individually ranked with a skill level of 1-10.


You're asked to provide 2 teams with an equal amount of people, and as close to equal skill level as possible.



My Answer:
Here is a scalable solution in PHP to create two teams of equal size and skill level:

php
function createTeams($players) {
// Sort players by skill level
usort($players, function($a, $b) {
return $a['skill'] <=> $b['skill'];
});

$team1 = [];
$team2 = [];
$totalSkillTeam1 = 0;
$totalSkillTeam2 = 0;

foreach ($players as $player) {
// Assign player to team with lower total skill
if ($totalSkillTeam1 <= $totalSkillTeam2) {
$team1[] = $player;
$totalSkillTeam1 += $player['skill'];
} else {
$team2[] = $player;
$totalSkillTeam2 += $player['skill'];
}
}

return ['Team 1' => $team1, 'Team 2' => $team2];
}

// Example array of players with skill levels
$players = [
['name' => 'Player 1', 'skill' => 7],
['name' => 'Player 2', 'skill' => 5],
['name' => 'Player 3', 'skill' => 8],
// Add more players here
];

$teams = createTeams($players);

echo "Team 1:\n";
foreach ($teams['Team 1'] as $player) {
echo $player['name'] . " (Skill: " . $player['skill'] . ")\n";
}

echo "\nTeam 2:\n";
foreach ($teams['Team 2'] as $player) {
echo $player['name'] . " (Skill: " . $player['skill'] . ")\n";
}


This solution sorts the players by skill level and then assigns them to teams based on their skill level, alternating between the two teams to keep the skill levels as balanced as possible. This algorithm can easily handle adding more players in the future while still maintaining balanced teams.

Rate this post

3 of 5 based on 4273 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us