使用r,很容易生成一次取m的x元素的所有组合。
> combn(c(0.4, 0.3, 0.7), 2)
[,1] [,2] [,3]
[1,] 0.4 0.4 0.3
[2,] 0.3 0.7 0.7
但实际上我想要一些略有不同的东西。我希望有相同的矩阵,但如果未选择该元素,则添加(1-x)。在前面的例子中,我会给出:
> specialcombn(c(0.4, 0.3, 0.7), 2)
[,1] [,2] [,3]
[1,] 0.4 0.4 (1-0.4)
[2,] 0.3 (1-0.3) 0.3
[3,] (1-0.7) 0.7 0.7
我写了(1-0.7)
...更明确,但我实际上只需要值(1-0.7) = 0.3
:p
我可以通过循环和高度复杂来做到这一点。我对一个好的(可能是最优的)解决方案感兴趣。
答案 0 :(得分:2)
这是一种非常通用的方法,它将返回一个精确排序的矩阵:
function myWebService(param1, param2, param3) {
$.ajax({
type: "POST",
url: "Default.aspx/MyMethod", // will make AJAX call to your code-behind code
// rest of you code...
});
}
如果您将它用于非常大的矩阵,则瓶颈可能是set <- c(0.4, 0.3, 0.7, 2, 0) # set to pick from
pick <- 3 # how many items to pick
comb <- combn(set, pick) # record combinations
# build matrix repeating the set once for each combination
x <- matrix(rep(set, ncol(comb)), nrow = length(set), ncol = ncol(comb))
# build a Boolean mask of values _not_ in each combination
mask <- apply(comb, 2, function(y){!set %in% y})
x[mask] <- 1 - x[mask] # use mask to subtract those numbers from 1
x
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,] 0.4 0.4 0.4 0.4 0.4 0.4 0.6 0.6 0.6 0.6
# [2,] 0.3 0.3 0.3 0.7 0.7 0.7 0.3 0.3 0.3 0.7
# [3,] 0.7 0.3 0.3 0.7 0.7 0.3 0.7 0.7 0.3 0.7
# [4,] -1.0 2.0 -1.0 2.0 -1.0 2.0 2.0 -1.0 2.0 2.0
# [5,] 1.0 1.0 0.0 1.0 0.0 0.0 1.0 0.0 0.0 0.0
,这可能会被设置操作所取代。除此之外,一切都应该是非常活泼的。
如果您不关心订单,可以跳过构建%in%
和掩码,只需x
1 - 将附加条款直接发送到rbind
:
comb
请注意,列中的顺序现在是不规则的。无论如何,要么应该使用任何给定大小的rbind(comb, apply(comb, 2, function(x){1 - (set[!set %in% x])}))
# [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
# [1,] 0.4 0.4 0.4 0.4 0.4 0.4 0.3 0.3 0.3 0.7
# [2,] 0.3 0.3 0.3 0.7 0.7 2.0 0.7 0.7 2.0 2.0
# [3,] 0.7 2.0 0.0 2.0 0.0 0.0 2.0 0.0 0.0 0.0
# [4,] -1.0 0.3 0.3 0.7 0.7 0.7 0.6 0.6 0.6 0.6
# [5,] 1.0 1.0 -1.0 1.0 -1.0 0.3 1.0 -1.0 0.3 0.7
和set
。