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
Click For Summary

Discussion Overview

The discussion revolves around creating a MATLAB code for a user to play a game of blackjack, specifically focusing on how to select a random subset of cards from a predefined deck.

Discussion Character

  • Homework-related
  • Technical explanation

Main Points Raised

  • One participant presents a matrix representing a deck of cards and seeks assistance in selecting a random subset of 2 cards.
  • Another participant suggests using the 'rand' function combined with 'round' to generate random indices for card selection.
  • A participant shares their updated code and expresses confusion regarding an error in their for loop when attempting to implement a hit option in the game.
  • Another participant points out an error in the for loop structure and provides a corrected version of the loop.

Areas of Agreement / Disagreement

Participants appear to be collaboratively refining the code, but there is no consensus on the overall implementation as issues remain unresolved.

Contextual Notes

The discussion includes potential issues with generating random indices and the handling of user input, which may affect the functionality of the code.

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