I have a mathematical problem in my JavaScript code. I need to divide a given number of players into 2 teams randomly so that each time – if players want to play again – the teams are formed again and they should be different until all the combinations are formed.
Let's say I have 4 players, so all the combinations are as follows:
[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]
However, because the team side doesn't count, there are only 3 different combinations:
[1,2] vs [3,4]
[1,3] vs [2,4]
[1,4] vs [2,3]
When the number of games played exceeds the number of combinations, it should start all over again... i.e. randomly selecting one of the three combination, randomly selecting next one and so on...
But there's a twist... and mathematical skills of mine go pretty hard south when the number of players is odd, and one of the player needs to rest one game. So, with 5 players all the match-up combinations are (last number being the player resting):
[1,2] vs [3,4] [5]
[1,2] vs [3,5] [4]
[1,2] vs [4,5] [3]
[1,3] vs [2,4] [5]
[1,3] vs [2,5] [4]
[1,3] vs [4,5] [2]
[1,4] vs [2,3] [5]
[1,4] vs [2,5] [3]
[1,4] vs [3,5] [2]
[1,5] vs [2,3] [4]
[1,5] vs [2,4] [3]
[1,5] vs [3,4] [2]
[2,3] vs [4,5] [1]
[2,4] vs [3,5] [1]
[2,5] vs [3,4] [1]
How is it possible in JavaScript to get those teams formed?
One thing that came into mind was to give each player an unique value (10^x), e.g.:
player1.value = 10;
player2.value = 100;
player3.value = 1000;
player4.value = 10000;
...and then when looping to form teams check if one the team's total value is equal to last values.
Could someone mathematically/JavaScriptly more talented please help me with this coding problem. Thanks!