%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% PERMUTATIONS PROCESSOR %
% %
% August 5th, 2013 %
% %
% by %
% Juan Ignacio Mendoza %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% ALL POSSIBLE PERMUTATIONS FOR A SEQUENCE AND THEN CONCATENATED WITHOUT %
% REPEATING TERMS %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clearvars
v = [1 2 3 4 5]; % <-------- numbers for permutations (be careful, over 7 might take a long time increasing factorially)
p1 = perms(v); % returns matrix p with all possible permutations (nrows = v!)
colv = size(v,2);
p2 = p1(randperm(size(p1,1)),:); % p2 is p1 rows randomised
% -------------------------------------------------------------------------
% Orders rows with the last term of each row matching the first of the
% next:
p3 = p2;
rowsp3 = (size(p3,1));
%pind = 1;
p4(1,1:colv) = p3(1,1:colv); % copy firt row in p3 to p4...
p3(1,1:colv) = NaN; % ...and replace it with NaN to avoid duplication
it = 0;
% while (size(p4,1)) < (size(p3,1)) % find a combination with all the sequences
% it = it +1;
for i1 = 1:rowsp3 % evaluate each row in p4 against each row in p3
last = p4((size(p4,1)),colv); % 'last' is the last term of this row
for i2 = 1:rowsp3 % search for a row in p3...
if p3(i2,1) == last % ...starting with 'last'
p4(i1+1,1:colv) = p3(i2,1:colv); % copy this row to p4...
p3(i2,1:colv) = NaN; % ...replace it with NaN to avoid duplication...
break % ...break loop and go to next row
else
end
end
end
%end
%clc;
%iter = sprintf('Iterations = %d', it);
%disp (iter);
rowsp4 = size(p4,1);
clc;
if rowsp4 == rowsp3
ok = sprintf('%d! (%d) combinations - Good.', colv, rowsp4);
disp (ok);
else
warn = sprintf('%d combinations - Should be %d! (%d). Please run script again.', rowsp4, colv, rowsp3);
disp (warn);
end
% -------------------------------------------------------------------------
p5 = p4(1:end,1:colv-1); % p5 contains all the possible combinations that present no repeated numbers when concatenated :-)
%%