MATLAB: Using loops to play blackjack

for loophomework

Use Matlab to calculate the odds of landing blackjack on the first hand dealt. REF: In blackjack you are dealt two cards from a standard deck of 52. There are:
4 Aces worth 11 points each (in your first two cards)
16 Jacks, Queens, Kings, and Ten-cards combined worth 10 points each
4 Nine-cards worth 9 points
4 Eight-cards worth 8 points
And so on down to two-cards
I.E. The probability of getting a 10 point card is 16/52 or 30.769%;
The probability of getting an Ace card is 4/52 or 7.692%;
To hit blackjack you MUST get an ace and a 10 card dealt (in either order)
Run this a different number of iterations, (try a high number) and report to the user what the average chance is of hitting blackjack.
As you likely know from statistics, the theoretical odds are (assuming ONE deck of cards): (4/52)*(16/51)+(16/52)*(4/51) or 4.83% Use to check your answer
Hint: Use a FOR loop (for number of attempts) and nested IF statements to calculate
count=0;
tries=10^7; %10 million tries; This will still run faster than 1 million iterations above using RANDI!
for i=1:tries
card1=rand; %1st card (random integer), 1-52
card2=rand; %2nd card (random integer), 2-52
card3=rand; %3rd card (random integer), 3-52
card4=rand; %4th card (random integer), 4-52
card5=rand; %5th card (random integer), 5-52
if card1<=(4/52) %4/52 chance of hitting the 1st card
if card2<=(16/51) %16/51 chance of hitting the same card on card 2
if card3<=(16/52) %16/52 chance on the 3rd card
if card4<=(4/51) %4/51 chance on the 4th card
%disp('You got 4 of a kind! Holy crap!'); %You can uncomment this to see how often you hit 4 of a kind while the code is running
count=(4/52)*(16/51)+(16/52)*(4/51);
end
end
end
end
end
chance=count/tries;
disp(['You hit 4 of a kind ' num2str(count) ' times, or'])
disp([num2str(chance*100) '% of the time.'])

Best Answer

I would just keep it simple
bj=0;
tries=1e7;
for i=1:tries
k=randperm(52);%simulates deck shuffle
if nnz(ismember(k(1:2),1:4))&nnz(ismember(k(1:2),5:20))%assign aces cards 1-5, and tens cards 5-21
bj=bj+1;
end
end
p=bj/tries
Related Question