Jake Thompson
Jake Thompson

Reputation: 2843

How to find all unique matches between two vectors?

I have two sets, and each element of one set can match with any element of the other set. For example, if I have sets {1, 2, 3} and {4, 5, 6}, the possible combinations are:

1, 4
2, 5
3, 6

1, 4
2, 6
3, 5

1, 5
2, 4
3, 6

1, 5
2, 6
3, 4

1, 6
2, 4
3, 5

1, 6
2, 5
3, 4

So when matching the two sets, there are 6 possible ways the 2 sets can be combined. Is there a way to determine all possible set combinations given two arbitrary vectors?

I’ve tried using tidyr::expand_grid(), but this gives all possible combinations of the two vectors without the constraint that each element can be matched with only one element from the other vector in any given set.

tidyr::expand_grid(set1 = c(1, 2, 3), set2 = c(4, 5, 6))
#> # A tibble: 9 × 2
#>    set1  set2
#>   <dbl> <dbl>
#> 1     1     4
#> 2     1     5
#> 3     1     6
#> 4     2     4
#> 5     2     5
#> 6     2     6
#> 7     3     4
#> 8     3     5
#> 9     3     6

Created on 2023-02-25 with reprex v2.0.2

Upvotes: 4

Views: 75

Answers (2)

jay.sf
jay.sf

Reputation: 73272

Using RcppAlgos::permuteGeneral to apply a FUNction that cbinds each permutation of v2 to v1.

RcppAlgos::permuteGeneral(v=v2, m=3, FUN=\(x) cbind(X1=v1, X2=x))
# [[1]]
#      X1 X2
# [1,]  1  4
# [2,]  2  5
# [3,]  3  6
# 
# [[2]]
#      X1 X2
# [1,]  1  4
# [2,]  2  6
# [3,]  3  5
# 
# [[3]]
#      X1 X2
# [1,]  1  5
# [2,]  2  4
# [3,]  3  6
# 
# [[4]]
#      X1 X2
# [1,]  1  5
# [2,]  2  6
# [3,]  3  4
# 
# [[5]]
#      X1 X2
# [1,]  1  6
# [2,]  2  4
# [3,]  3  5
# 
# [[6]]
#      X1 X2
# [1,]  1  6
# [2,]  2  5
# [3,]  3  4

Data:

v1 <- 1:3
v2 <- 4:6

Upvotes: 3

ThomasIsCoding
ThomasIsCoding

Reputation: 102251

I think you can fix the position of one vector, but enumerate all permutations of the other one and bind them to the previously fixed vector, such that you won't obtain isomorsphism among all combinations, e.g.,

> library(pracma)

> Map(cbind, list(v1), asplit(perms(v2), 1))
[[1]]
     [,1] [,2]
[1,]    1    6
[2,]    2    5
[3,]    3    4

[[2]]
     [,1] [,2]
[1,]    1    6
[2,]    2    4
[3,]    3    5

[[3]]
     [,1] [,2]
[1,]    1    5
[2,]    2    6
[3,]    3    4

[[4]]
     [,1] [,2]
[1,]    1    5
[2,]    2    4
[3,]    3    6

[[5]]
     [,1] [,2]
[1,]    1    4
[2,]    2    5
[3,]    3    6

[[6]]
     [,1] [,2]
[1,]    1    4
[2,]    2    6
[3,]    3    5

Upvotes: 4

Related Questions