shuffling cards using only simple cuts

1 view (last 30 days)
Hello,
I am trying to write a code to split a deck of cards at a random point, then join the two halves back together with half 2 in front of half 1 instead of behind. This is where my code is at right now:
clear
clc
Deck = ["D1" "D2" "D3" "D4" "D5" "D6" "D7" "D8" "D9" "D10" "DJ" "DQ" "DK" "H1" "H2" "H3" "H4" "H5" "H6" "H7" "H8" "H9" "H10" "HJ" "HQ" "HK" "C1" "C2" "C3" "C4" "C5" "C6" "C7" "C8" "C9" "C10" "CJ" "CQ" "CK" "S1" "S2" "S3" "S4" "S5" "S6" "S7" "S8" "S9" "S10" "SJ" "SQ" "SK"];
Deckinit = Deck;
for n = 1:1
split = randi([2 length(Deck)-1],1,1);
Deck1 = zeros(1,split);
Deck2 = zeros(1,length(Deck)-split);
for k = 1:split
Deck1(k) = Deck(k);
end
for k = split+1:length(Deck)
Deck2(k - split) = Deck(k);
end
Deck = [Deck2 Deck1];
end
The only issue is, sometimes it runs and Deck is 1x52, which is what I expect, and sometimes it includes NaN elements and is of wildly different lengths. I think it has something to do with some values for split working and some not. Any and all help is appreciated!
  1 Comment
Tim Bentley
Tim Bentley on 15 Apr 2020
clear
clc
Deck = ["D1" "D2" "D3" "D4" "D5" "D6" "D7" "D8" "D9" "D10" "DJ" "DQ" "DK" "H1" "H2" "H3" "H4" "H5" "H6" "H7" "H8" "H9" "H10" "HJ" "HQ" "HK" "C1" "C2" "C3" "C4" "C5" "C6" "C7" "C8" "C9" "C10" "CJ" "CQ" "CK" "S1" "S2" "S3" "S4" "S5" "S6" "S7" "S8" "S9" "S10" "SJ" "SQ" "SK"];
Deckinit = Deck;
for n = 1:1
split = randi([2 length(Deck)-1],1,1);
for k = 1:split
Deck1(k) = Deck(k);
end
for k = split+1:length(Deck)
Deck2(k - split) = Deck(k);
end
Deck = [Deck2 Deck1];
end
removing the two zeros() lines is more computationally expensive but stops the NaN issue

Sign in to comment.

Accepted Answer

the cyclist
the cyclist on 15 Apr 2020
split = randi(numel(Deck)-1);
Deck = [Deck(split+1:end),Deck(1:split)];

More Answers (0)

Categories

Find more on Get Started with MATLAB in Help Center and File Exchange

Products

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!