首页 > 代码库 > 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。