Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 264
Jake Thompson Avatar asked Oct 14 '25 11:10

Jake Thompson


1 Answers

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
like image 89
ThomasIsCoding Avatar answered Oct 17 '25 00:10

ThomasIsCoding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!