Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I would like, from a given array, to generate all the arrays obtained by swapping every possible couple of elements in an array, basically $\frac{n \cdot (n-1)} {2} $. What is the simplest way to make it ?

[EDIT] :For example, if I have [1 2 3 4] array, I would to 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]

like image 591
MysteryGuy Avatar asked Dec 07 '17 11:12

MysteryGuy


1 Answers

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 row of the result contains the input with 2 elements swapped. The swappings are done in lexicographical order. So in the first row elements 1 and 2 are swapped; in the second row elements 1 and 3 are swapped; ... ; in the last row elements 3 and 4 are swapped.

like image 98
Luis Mendo Avatar answered Nov 01 '22 10:11

Luis Mendo