首页 > 代码库 > matlab deckShuffling

matlab deckShuffling

% a script to determine how many perfect shuffles are required
% before a given deck of cards returns to its original order

clear all, close all

% problem statement:
% suppose we have a deck of 8 (distinct) cards
% 1 2 3 4 5 6 7 8

% define a perfect shuffle as interleaving the cards as follows
% 1 5 2 6 3 7 4 8

% in other words, given a deck of an even number of distinct cards,
% divide the deck in half,
% then alternately insert cards from the bottom half into the top half

% for a deck of 8 cards, it is easily seen that the original order
% is obtained after 3 applications of this process

% the task is to write a program that tests this out for N cards,
% where we are particularly interested in the case N=52, 
% the size of a standard deck of cards

% here are the basic steps:
% get the size of the deck
% check that the input is valid
% initialize deck to unique cards
% repeat:
%    perfectly shuffle the deck
%    keep track of how many shuffles have been made
% until: original order has been obtained

disp(‘Counting perfect shuffles of decks with an even number of cards.‘)
disp(‘ ‘)

N = input(‘Please enter size of deck: ‘);

% check that N is a (positive!) even number; else fail
if ((N < 0) | (rem(N,2) ~= 0)),
  error(‘Deck must contain an even number of cards.‘);
end

% initialize deck to unique cards
originalDeck = [1:N]‘;
shuffles     = 0;

% perform the first shuffle explicitly
shuffledDeck = perfectShuffle(originalDeck);
shuffles     = shuffles + 1;

while (~isequal(shuffledDeck,originalDeck)),
  shuffledDeck = perfectShuffle(shuffledDeck);
  shuffles     = shuffles + 1;
end

disp([‘A deck of size ‘, num2str(N), ‘ requires ‘, num2str(shuffles), ...
       ‘ perfect shuffles before it returns to its original state.‘])

matlab deckShuffling