Goal
Imagine a even number of individuals that have to create teams of two people. Each individual has to call a R function and enter two parameters; 1) Their own name and 2) the names of the other individuals in the order of their preference. When everyone has voted a function extracts the best combination of teams. The goal is to construct this function.
Example
John, Peter, Mary and Jessica need to construct teams of two people. John preferentially wants to be with Peter, moderatly with Mary and would prefer not be with Jessica. Therefore John enters the following code line:
Create_binom(MyName='John', Preferences = c('Peter', 'Mary', 'Jessica'))
The three other players do the same, they enter their names and their preferences:
Create_binom(MyName='Mary', Preferences = c('Peter', 'Jessica', 'John'))
Create_binom(MyName='Peter', Preferences = c('John', 'Jessica', 'Mary'))
Create_binom(MyName='Jessica', Preferences = c('Mary', 'John', 'Peter'))
At the last call (when the last player called the function entering its name and preferences), the function recognizes that all players have indicated their preferences and the function create the best combinations of 2-people teams and print it. The best combination is defined as the combination that minimizes the sum of the positions of the teammates in the preferences of all players. We'll call this sum the "index" of the combination.
Index of a combination
The combination (John with Mary) and (Peter with Jessica) has associated index 2 + 3 + 2 + 3 = 10.
The combination (Mary with Jessica) and (Peter with John) has associated index 1 + 1 + 2 + 1 = 5. With this combination only one player (Mary) will not play with her best friend! It is the best possible solution in my example.
Of course, in a perfect world, everybody would be associated with his/her best friend and the index of the perfect combination would equal the number of players, but this is often not possible.
Output of the example (Best combination for the example)
Here is what the function should print out:
list(c("Peter", "John"),c("Mary", "Jessica"))
...or any of the 8 equivalents results.
Special case
Of course if there are several best combinations, then the function should just pick one of the best combination at random.