Permutation and combination to flip the numbers in the array

2 views (last 30 days)
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
Abhishek Gangwar on 22 Jul 2020
Give a proper example, that will be better to understand the problem statement.
Yang Metin
Yang Metin on 24 Jul 2020
Give a more detailed example
[1 1 1 1 1] The result of flipping 2 is
[0 0 1 1 1], [1 0 0 1 1], [1 1 0 0 1], [1 1 1 0 0], [0 1 0 1 1], [0 1 1 0 1], [0 1 1 1 0], [1 0 1 0 1], [1 0 1 1 0] etc.
Flip means 0->1,1->0.
I need all the results, including more 01 combinations and the number of flips.

Sign in to comment.

Accepted Answer

Bruno Luong
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

More Answers (1)

Bruno Luong
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
Yang Metin
Yang Metin on 24 Jul 2020
I wrote a more detailed example in the topic comment, what you gave is part of it.
Bruno Luong
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

Sign in to comment.

Categories

Find more on Matrices and Arrays in Help Center and File Exchange

Tags

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!