我想生成前n个整数的所有排列,使得指定的整数组保留在它们的组中,并且组保持相同的顺序。例如,如果我们有n = 5和分组[[1],[2,3],[4,5]],那么我想输出
[[1],[2,3],[4,5]]
[[1],[2,3],[5,4]
[[1],[3,2],[4,5]]
[[1],[3,2],[5,4]
每个排列应该在矩阵中显示为一行,我刚刚包含括号表示法以便于查看分组。就我而言,数字1始终是每个排列的第一个元素。我已经尝试生成每个组的所有排列,然后将它们粘贴到矩阵中适当的次数,但是不能找出循环组的一般方法,使得排列不重复。这是我的代码:f是一个向量,其中f(i)是组i的起始索引,r是一个向量,使得r(i)是组i中元素的数量。
function AP=allPerms(f,r)
%Construct all possible permutations of integers consistent with their
%grouping
n=length(r); %Number of groups
num_parts=f(n)+r(n)-1; %Number of integers
num_perms=factorial(r(1)-1); %Initialize num of perms
for i=2:n
num_perms=num_perms*factorial(r(i)); %Formula for num_perms
end
AP=zeros(num_perms,num_parts); %Initialize matrix to store perms
AP(:,1)=ones(num_perms,1); %First column is all 1's
%handle case where there is only 1 group
if n==1
AP(:,2:num_parts)=perms(2:num_parts);
return
end
%Construct all the sublist perms
v{1}=perms(2:f(2)-1); v{n}=perms(f(n):f(n)+r(n)-1);
for i=2:n-1
v{i}=perms(f(i):f(i+1)-1);
end
%Insert into perm array appropriate number of times. consider i=1,n
%seperately
if r(1)~=1
for j=1:num_perms/factorial(r(1)-1)
AP((j-1)*factorial(r(1)-1)+1:j*factorial(r(1)-1),2:f(1)+r(1)-1)=v{1};
end
end
for i=2:n-1
for j=1:num_perms/factorial(r(i))
AP((j-1)*factorial(r(i))+1:j*factorial(r(i)),f(i):f(i)+r(i)-1)=v{i};
end
end
for j=1:num_perms/factorial(r(n))
AP((j-1)*factorial(r(n))+1:j*factorial(r(n)),f(n):f(n)+r(n)-1)=v{n};
end
端
我尝试在j上的循环中使用circshift来获得不同的排列,并且可以使其适用于特定情况,但不是一般的。有没有系统的方法来做到这一点?我不想生成所有排列,然后过滤它们。
我也发现了这篇论文:
https://arxiv.org/pdf/1311.3813.pdf
我想知道在我尝试实现此功能之前是否存在可能有效的解决方案。
答案 0 :(得分:0)
以下是基于cellfun
,perms
和ndgrid
grouping={1,[2 3],[4 5]};
perm = cellfun(@(x){perms(x)},grouping); %for each group generate all permutations
cart = cell(1,numel(grouping));
perm_size = cellfun(@(x){1:size(x,1)},perm); % [1 : size_of_permutation] to be used in ndgrid
[cart{:}]=ndgrid(perm_size{:}); % Cartesian product of indexes of permutations
result = cell(1,numel(grouping));
for k = 1:numel(cart)
result(k) = perm{k}(cart{k},:); % In the loop index permutations with the cartesian product of their indexes
end
结果如下:
result =
{
[1,1] =
1
1
1
1
[1,2] =
2 3
3 2
2 3
3 2
[1,3] =
4 5
4 5
5 4
5 4
}