我想知道是否有一个简单的解决方案来查找向量与重复元素的所有组合。实际应用是组合数学。例如:
有一个瓮,里面有 2 个红球和 2 个黑球,有多少种不同的方式可以抽出所有 4 个球。
我能找到的唯一解决方案如下,但我确信必须有更简单的代码来生成它?谢谢您的帮助。
combin <- permutations(n = 4, r = 4, v = 1:4)
# mapping
#1 -> 1 : Red
# 2-> 1 : Red
# 3-> 0 : Black
#4 -> 0 : Black
combin<-replace(combin, combin == 2, 1)
combin <- replace(combin, combin == 3, 0)
combin <- replace(combin, combin == 4, 0)
combin <- unique(combin)
combin
[,1] [,2] [,3] [,4]
[1,] 1 1 0 0
[2,] 1 0 1 0
[3,] 1 0 0 1
[4,] 0 1 1 0
[5,] 0 1 0 1
[6,] 0 0 1 1
定义 urn 并提及此示例将使用的包。
# library(combinat)
# library(gtools)
# library(RcppAlgos)
urn <- c("red", "red", "black", "black")
创建于 2024-09-08,使用 reprex v2.1.0
首先是包的排列
combinat
。
urn <- c("red", "red", "black", "black")
combinat::permn(urn) |> do.call(rbind, args = _) |> unique()
#> [,1] [,2] [,3] [,4]
#> [1,] "red" "red" "black" "black"
#> [2,] "red" "black" "red" "black"
#> [3,] "black" "red" "red" "black"
#> [4,] "black" "red" "black" "red"
#> [5,] "red" "black" "black" "red"
#> [6,] "black" "black" "red" "red"
创建于 2024-09-08,使用 reprex v2.1.0
现在有包装
gtools
。这更复杂,因为函数 gtools::permutations
仅对所有元素都不同的向量进行排列。
i <- gtools::permutations(4, 4, seq_along(urn))
apply(i, 1L, \(j) urn[j]) |> t() |> unique()
#> [,1] [,2] [,3] [,4]
#> [1,] "red" "red" "black" "black"
#> [2,] "red" "black" "red" "black"
#> [3,] "red" "black" "black" "red"
#> [4,] "black" "red" "red" "black"
#> [5,] "black" "red" "black" "red"
#> [6,] "black" "black" "red" "red"
urn |>
seq_along() |>
gtools::permutations(4, 4, v = _) |>
apply(1L, \(i) urn[i]) |>
t() |>
unique()
#> [,1] [,2] [,3] [,4]
#> [1,] "red" "red" "black" "black"
#> [2,] "red" "black" "red" "black"
#> [3,] "red" "black" "black" "red"
#> [4,] "black" "red" "red" "black"
#> [5,] "black" "red" "black" "red"
#> [6,] "black" "black" "red" "red"
创建于 2024-09-08,使用 reprex v2.1.0
最后,有了高性能包
RcppAlgos
。
RcppAlgos::permuteGeneral(urn, 4L) |> unique()
#> [,1] [,2] [,3] [,4]
#> [1,] "red" "red" "black" "black"
#> [2,] "red" "black" "red" "black"
#> [3,] "red" "black" "black" "red"
#> [4,] "black" "red" "red" "black"
#> [5,] "black" "red" "black" "red"
#> [6,] "black" "black" "red" "red"
创建于 2024-09-08,使用 reprex v2.1.0