%% The Perfect Shuffle
% In a perfect shuffle, or faro shuffle,  a deck of cards is divided into equal halves then perfectly interleaved. You will end up with the first card from the left half followed by the first card from the right half, etc. After repeatedly performing  perfect shuffles on an even-sized deck of  cards, the return to its original order.
% Here are six examples indicating how long the deck returns to its original order for an Out Shuffle.

% from https://rosettacode.org/wiki/Perfect_shuffle#MATLAB
Result=[]; 
Q=[8, 24, 52, 100, 1020, 1024]; 
for n=Q 
    Same=0; 
    T=0; 
    while ~Same 
        T=T+1; 
        R=PerfectShuffle(n,T); 
        Same=~(any(R-(1:n))); 
    end 
    Result=[Result;T]; 
end
disp([Q', Result])

%
% The case for eight cards is easy to list. We extract part of the previous code to display the results of each shuffle.

n=8;
Same=0; 
    T=0; 
    while ~Same 
        T=T+1; 
        R=PerfectShuffle(n,T) 
        Same=~(any(R-(1:n))); 
    end

%

function [New]=PerfectShuffle(Nitems, Nturns)
    if mod(Nitems,2)==0     %only if even number
        X=1:Nitems;         %define deck
        for c=1:Nturns      %defines one shuffle
            X=reshape(X,Nitems/2,2)';   %split the deck in two and stack halves
            X=X(:)';        %mix the halves
        end
        New=X;              %result of multiple shufflings
    end
end