-1

I am trying to simulate a game of poker where I am required to distribute cards to "n" number of players playing at one point. I have written a brief piece of code that looks at the existing deck and gives out cards to other players however this is quite hard coded. I wonder if there is a way to do this activity without hard coding using "loop where one could define the number of players and the code is able to look the revised deck and gives new cards to other players. Here is what I have written so far:

Player_1 <- cards[sample(nrow(cards), 2), ]
Player_1

Remaining_Deck <- sqldf('SELECT * FROM cards EXCEPT SELECT * FROM Player_1') # subset from t1 not in t2 

Player_2 <- cards[sample(nrow(Remaining_Deck), 2), ]
Player_2

Remaining_Deck2 <- sqldf('SELECT * FROM Remaining_Deck EXCEPT SELECT * FROM Player_2') # subset from t1 not in t2 

Player_3 <- cards[sample(nrow(Remaining_Deck2), 2), ]
Player_3

Remaining_Deck3 <- sqldf('SELECT * FROM Remaining_Deck2 EXCEPT SELECT * FROM Player_3') # subset from t1 not in t2 

Player_1
Player_2
Player_3
R. Schifini
  • 9,085
  • 2
  • 26
  • 32
Ayan CH
  • 1
  • 4
  • `sample(cards)` will shuffle the deck, then go assigning cards from index 1 and removing them from the deck. There is no need to reshuffle. – R. Schifini Nov 04 '16 at 12:43

1 Answers1

1

Why are you re-shuffling each time you deal a card? Instead, shuffle once, then track the index of the card to deal. You could, if you really wanted, remove the cards, but that is unnecessary.

First, generate the deck (this is easier as a vector, unless you have other info attached to the cards):

cards <-
  as.character(outer(
    c(2:10, "J", "Q", "K", "A")
    , c("S", "H", "D", "C")
    , paste
    , sep = "_"
  ))

Then, shuffle for this hand:

deckThisHand <- sample(cards)

Set the index to deal the top card:

currCardToDeal <- 1

Then, start dealing. Note, I included a variable to store the number to deal, though this is not strictly necessary. Just makes it easier if you ever change from hold-em to five card draw.

nToDeal <- 2

player1 <- deckThisHand[currCardToDeal:(currCardToDeal+nToDeal-1)]

currCardToDeal <- currCardToDeal+nToDeal-1

Then, you can iterate over players:

player2 <- deckThisHand[currCardToDeal:(currCardToDeal+nToDeal-1)]

currCardToDeal <- currCardToDeal+nToDeal-1

player3 <- deckThisHand[currCardToDeal:(currCardToDeal+nToDeal-1)]

currCardToDeal <- currCardToDeal+nToDeal-1
Mark Peterson
  • 9,370
  • 2
  • 25
  • 48