B是[1x8]矩阵,也可以认为是两半:
B = -1 -1 0 0 0 0 1 1
这里的前半部分可以有一个,两个,三个或四个-1
,下半部分应该有1
个相同的数量。它应该以线性组合完成。
例如,如果上半部分中有两个-1
,则可以4 choose 2 = 6
方式放置它们,并且对于每个{...}}方式,将有6种方式放置这两个1
-1
1}}在下半场。因此系统总共有6 * 6 = 36种方式。如果在上半场有两个{{1}},那么B的36个不同的值。
我该怎么做?
答案 0 :(得分:5)
你可以先生成1和0的所有可能的排列,然后扔掉多余的排列。
%# make permutations using dec2bin (start from 17 since it's the first solution)
allB = str2double(num2cell(dec2bin(17:255)));
%# change sign in the first half, then check that the total is ok
allB(:,1:4) = - allB(:,1:4);
allB = allB(sum(allB,2)==0,:);
allB
的每一行都是B
答案 1 :(得分:2)
这是另一种解决方案:
%# generate all possible version of first half
h1 = num2cell(-(dec2bin(1:15)-'0'),2);
%# generate all possible version of second half
h2 = arrayfun(@(i) unique(perms([zeros(1,4-i) ones(1,i)]),'rows'), (1:4)', 'UniformOutput',false);
%'# number of 1s in each row of h1
n = -cellfun(@sum, h1);
%# get final result by combining h1 and h2
B = cellfun(@(a,b) [repmat(a,size(b,1),1) b], h1, h2(n), 'UniformOutput',false);
B = cell2mat(B);
结果:
B =
0 0 0 -1 0 0 0 1
0 0 0 -1 0 0 1 0
0 0 0 -1 0 1 0 0
0 0 0 -1 1 0 0 0
0 0 -1 0 0 0 0 1
0 0 -1 0 0 0 1 0
0 0 -1 0 0 1 0 0
0 0 -1 0 1 0 0 0
0 0 -1 -1 0 0 1 1
0 0 -1 -1 0 1 0 1
0 0 -1 -1 0 1 1 0
0 0 -1 -1 1 0 0 1
0 0 -1 -1 1 0 1 0
0 0 -1 -1 1 1 0 0
0 -1 0 0 0 0 0 1
0 -1 0 0 0 0 1 0
0 -1 0 0 0 1 0 0
0 -1 0 0 1 0 0 0
0 -1 0 -1 0 0 1 1
0 -1 0 -1 0 1 0 1
0 -1 0 -1 0 1 1 0
0 -1 0 -1 1 0 0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