Using R for a random pair of elements not in the same group

I write an algorithm in R to randomly pair people, but people in a pair cannot be from the same group (team).

I started by creating the nxn matrix of all people. I marked 0 to indicate people who cannot mate together (if they are on the same team) and 1 otherwise.

Problem: Now I need to select from the list of suitable people (all 1) in each row and mark a pair and make sure that two people in this pair can no longer be connected to another person.

eg.

Title - Team

A - 1

B - 2

C - 3

D - 4

E - 1

F - 2

G - 1

  A B C D E F G
A 0 1 1 1 0 1 0
B 1 0 1 1 1 0 1
C 1 1 0 1 1 1 1
D 1 1 1 0 1 1 1
E 0 1 1 1 0 1 0
F 1 0 1 1 1 0 1
G 0 1 1 1 0 1 0

, , , , , 5 .

, , , .

(, ), , , .

.

+4
1

Try

 (!tcrossprod(table(df1)))+0L

df1 <- structure(list(Name = c("A", "B", "C", "D", "E", "F", "G"), 
Team = c(1L, 
2L, 3L, 4L, 1L, 2L, 1L)), .Names = c("Name", "Team"),
 class =  "data.frame", row.names = c(NA, -7L))
+5

Source: https://habr.com/ru/post/1583792/


All Articles