Home How to generate all the permutations of two elements in an array?
Reply: 1

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

MysteryGuy
1#
MysteryGuy Published in 2017-12-07 11:00:01Z

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]

Luis Mendo
2#
Luis Mendo Reply to 2017-12-07 11:51:58Z

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.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.394151 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO