有什么简单的方法可以从k值中生成长度N的排列吗?示例:
N = 2
k = [[0 0], [0 1], [1 0], [1 1]]
Permutations = [
[[0 0], [0 0]],
[[0 0], [0 1]],
[[0 0], [1 0]],
[[0 0], [1 1]],
[[0 1], [0 0]],
[[0 1], [0 1]],
[[0 1], [1 0]],
[[0 1], [1 1]],
...
]这里有一个重要的注意事项:如果可能的话,我希望结果一直是数组(迭代器包中的product函数生成元组)。
如果有用的话,Haskell的等价物应该是:replicateM 2 [[0, 0], [0, 1], [1, 0], [1, 1]]
为了防止有一种更地道的方法来实现我想要做的事情,下面是我正在编写的函数:
function generate_states(length)
# "tuples" contains what I want, but it needs a lot of transformation to
# be usable later
tuples = [collect(t) for t in
product([product(0:1, 0:1) for _ in 1:length]...)]
states = collect(distinct(imap(x -> kron([[i...] for i in x]...), tuples)))
return states
end它可以工作,可以做我想做的事情,但理想的情况是,我希望它看起来像这样:
function generate_states(length)
arrays = replicateM(3, Array[[0 0], [0 1], [1 0], [1 1]])
states = collect(distinct(imap(x -> kron(x...), arrays)))
return states
end发布于 2016-03-08 15:06:18
更新/修复
这个问题实际上想要从N生成k元素的所有长度序列。
这可以通过以下方式实现:
using Iterators # install package with `Pkg.add("Iterators")`
N = 2
k = Array[[0 0], [0 1], [1 0], [1 1]]
res = [Array[e...] for e in product(fill(k,N)...)]旧解释.对象的排列
collect(combinations(['a','b','c','d'],2))生成正确的集合,而不考虑正在配置的元素。
代码[0 0]中的特定元素是行向量(即1x2矩阵)。这比Julia中的列向量更尴尬。列向量的示例是:
julia> combinations(Array[[0,0],[0,1],[1,0],[1,1]],2) |> collect
6-element Array{Array{Array{Int64,1},1},1}:
[[0,0],[0,1]]
[[0,0],[1,0]]
[[0,0],[1,1]]
[[0,1],[1,0]]
[[0,1],[1,1]]
[[1,0],[1,1]]注意[]的显式类型,以防止vcat将内部元素压平。使用行向量,如OP中所示:
combinations(Array[[0 0],[0 1],[1 0],[1 1]],2) |> collect(标准输出混乱)
发布于 2016-03-08 23:43:45
对于元组有一个简单的解决方案,如下所示:
K = [(0,0), (0,1), (1,0), (1,1)]
vec( [(i,j) for i in K, j in K] )如果您真的需要数组(为什么需要这个?)你可以做到
K2 = [ [a...] for a in K ]
[ a for a in vec( [(i,j) for i in K2, j in K2] ) ]如果您需要数组,那么这也是可能的,但更混乱。所以问题是,你真的不能用元组吗?
https://stackoverflow.com/questions/35864784
复制相似问题