Permutation and combination to flip the numbers in the array
2 views (last 30 days)
Show older comments
There is a set of numbers such as [1 0 1 0 1 1], and now I need to flip two of them arbitrarily, such as flipping the first and the second, then the result is [0 1 1 0 1 1], I need to enumerate all flipped result.
The array (only 01) and the number of flips are variables. How to write a program?
6 Comments
Abhishek Gangwar
on 22 Jul 2020
Give a proper example, that will be better to understand the problem statement.
Accepted Answer
Bruno Luong
on 24 Jul 2020
Edited: Bruno Luong
on 24 Jul 2020
A = logical([1 0 1 0 1 1])
nflip = 2;
m = size(A, 2);
j = nchoosek(1:m, nflip);
i = repmat((1:size(j,1))', [1,size(j,2)]);
mask = accumarray([i(:) j(:)], 1);
F = xor(A,mask)
Result
A =
1×6 logical array
1 0 1 0 1 1
F =
15×6 logical array
0 1 1 0 1 1
0 0 0 0 1 1
0 0 1 1 1 1
0 0 1 0 0 1
0 0 1 0 1 0
1 1 0 0 1 1
1 1 1 1 1 1
1 1 1 0 0 1
1 1 1 0 1 0
1 0 0 1 1 1
1 0 0 0 0 1
1 0 0 0 1 0
1 0 1 1 0 1
1 0 1 1 1 0
1 0 1 0 0 0
0 Comments
More Answers (1)
Bruno Luong
on 23 Jul 2020
Edited: Bruno Luong
on 23 Jul 2020
If I understand the question correctly
A0=[1 0 1 0 1 1]
% A1 is all possible single swap (permutation of 2 elements) of
% binary vector A0 (Note: A0 itself is not listed)
i0=find(A0==0);
i1=find(A0==1);
[i0,i1]=ndgrid(i0,i1);
n=numel(i0);
A1=repmat(A0,n,1);
r=(1:n)';
A1(sub2ind(size(A1),r,i0(:)))=1;
A1(sub2ind(size(A1),r,i1(:)))=0;
% Display
A1
If you want to enumerate 2 swaps just iterate the above procedure again on the row results.
Etc...
2 Comments
Bruno Luong
on 24 Jul 2020
Edited: Bruno Luong
on 24 Jul 2020
OK, I missunderstood because you wrote "permutation" is the subject, which usually meant shuffle the array.
Solution is on the other ANSWER
See Also
Categories
Find more on Matrices and Arrays in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!