Blackjack Program -- Random Card Deal

4 views (last 30 days)
Amy Speer
Amy Speer on 15 Apr 2019
Answered: Steven Lord on 15 Apr 2019
I am trying to create a blackjack program that deals two random cards to the dealer, then from the remaining deck, deals two random cards to the player (cannot have the same card as the dealer). How do I eliminate the two cards that were dealt to the dealer from the deck before dealing the player?
This is my code so far:
%H-Hearts, D-Diamonds, S-Spades, C-Clubs
full_deck = ['A23456789TJQK'];
suit = ['HDSC'];
card1_dealer = randsample(full_deck, 1);
suit1_dealer = randsample(suit, 1);
card2_dealer = randsample(full_deck, 1);
suit2_dealer = randsample(suit, 1);
cards = [card1_dealer, suit1_dealer; card2_dealer, suit2_dealer]

Answers (1)

Steven Lord
Steven Lord on 15 Apr 2019
Deal 4 cards from the deck at once. Give the dealer the first two and the player the next two.
As written, your code can give the dealer the same card twice. Instead generate random numbers from 1 to 52 without replacement (you can use randperm to do this) then determine which rank and suit pair each of those numbers represents.
Hint: If you were to arrange the cards in a matrix like the example set in the "Rank and Color" section of the Wikipedia page for a 52-card deck, what linear index refers to, say, the 9 of spades? How about the 9 of hearts? The 10 of spades? Can you find a way, given a linear index, to compute which rank and suit that index represents?

Community Treasure Hunt

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

Start Hunting!