How to generate all permutations of two elements in an array?

I would like, from a given array, to generate all arrays obtained by replacing all possible pairs of elements in the array, basically $ \ frac {n \ cdot (n-1)} {2} $. What is the easiest way to do this?

[EDIT]: For example, if I have an array [1 2 3 4] , I would generate [1 3 2 4] , [1 2 4 3] , [1 4 3 2] , [2 1 3 4] , [3 2 1 4] and [4 2 3 1]

+5
source share
1 answer

You can use this:

 x = [10 20 30 40]; % example input array t = nchoosek(1:numel(x),2); % each row defines a swapping of two elements ind = bsxfun(@plus, (1:size(t,1)).', (t-1)*size(t,1)); % convert to linear index result = repmat(x, size(t,1), 1); % initiallize result as copies of the input result(ind) = result(fliplr(ind)); % do the swapping in each row 

In this example

 result = 20 10 30 40 30 20 10 40 40 20 30 10 10 30 20 40 10 40 30 20 10 20 40 30 

Each line of the result contains an input with two elements replaced. Transactions are performed in lexicographical order . Therefore, in the first row, elements 1 and 2 are interchanged; in the second line, elements 1 and 3 are replaced; ...; on the last line, items 3 and 4 are swapped.

+5
source

Source: https://habr.com/ru/post/1273921/


All Articles