How Can I Select a Random Subset of Cards in MATLAB for Blackjack?

  • Thread starter Thread starter physizl
  • Start date Start date
  • Tags Tags
    Matlab
AI Thread Summary
The discussion focuses on creating a MATLAB code for a blackjack game, specifically how to select a random subset of two cards from a predefined deck. The user initially struggles with the random selection using functions like randperm and randi but finds a solution using the round and rand functions. They also encounter issues with their for loop when trying to implement the "hit" functionality, leading to an error. The corrected for loop structure is suggested to properly handle the user's input for hitting. Overall, the thread provides insights into coding challenges and solutions for implementing a blackjack game in MATLAB.
physizl
Messages
9
Reaction score
0

Homework Statement



write a code for a user to play a game of blackjack

The Attempt at a Solution



I have

deck = ['AH';'2H';'3H';'4H';'5H';'6H';'7H';'8H';'9H';'TH';'JH';'QH';'KH';
'AS';'2S';'3S';'4S';'5S';'6S';'7S';'8S';'9S';'TS';'JS';'QS';'KS';
'AD';'2D';'3D';'4D';'5D';'6D';'7D';'8D';'9D';'TD';'JD';'QD';'KD';
'AC';'2C';'3C';'4C';'5C';'6C';'7C';'8C';'9C';'TC';'JC';'QC';'KC'];

but how do i get a random subset of 2 cards from this matrix??
tried randperm and randi... no luck :(

help me please!
 
Physics news on Phys.org
try

Code:
rnum = round(n*rand(1,2));
card1 = deck(rnum(1));
card2 = deck(rnum(2));

Where n is the number of cards you want to sample.
 
thanks that helps

so now i have:

Code:
h1 = round(12*rand(1,2))+1;
disp(['Dealer deals you: ' , num2str(h1) ] )
d1 = input('hit or pass? ');
for hit
    h2 = round(12*rand(1))+1; % user's new hand
    h12 = [h1 h2];
    disp(['Dealer deals... you get: ' , num2str(h12) ]) 
end

i have round(12*rand(1,2))+1 because round(13*rand(1,2)) gives me a zero sometimes.
what's wrong with my for loop? when i type hit for input, i get an error
 
Your for loop was developed incorrectly it should read:

Code:
for j=1:hit
    h2 = round(12*rand(1))+1; % user's new hand
    h12 = [h1 h2];
    disp(['Dealer deals... you get: ' , num2str(h12) ]) 
end
 
Back
Top