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.'])
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值