  function ShowAllPoss()
% Recursive and non-recursive methods for displaying all
% possible permutations of a string.

clc
% Nonrecursive handling of the length-4 case...
C = AllPoss4('abcd')'

% Recursive method...
%C = AllPoss('abcdef')
%M = length(C)



  function C = AllPoss(s,t)
% t and s are strings
% C is a cell array of all possible strings of the form [t p] where
% p is a permutation of s.
% A call of the form AllPoss(s) sets t = ''
if nargin==1
    t = '';
end
n = length(s);
if n==1
    % There is only one permutation of s and it is s itself...
    C = [t s];
else
    C = {};
    for k=1:length(s)
        % "Remove" s(k) from s...
        sNew = [s(1:k-1) s(k+1:n)];
        % "Add" s(k) to t
        tNew = [t s(k)];
        % Recursive call..
        Ck = AllPoss(sNew,tNew);
        % Augment C...
        C = [C;Ck];
    end       
end


  function C = AllPoss4(s)
% s is a length 4 string
% C is a cell array of strings that consisting of all permutations of s
k=0;
% The loops generate a permutation [i1 i2 i3 i4] of [ 1 2 3 4]...
for i1 = 1:4
    for i2=1:4
        if i1~=i2
           for i3=1:4
               if i3~=i1 && i3~=i2
                  for i4=1:4
                     if i4~=i1 && i4~=i2 && i4~=i3
                        k = k+1;
                        C{k} = [s(i1) s(i2) s(i3) s(i4)];
                     end
                  end
               end
           end
        end
    end
end

    