Skip to content

Instantly share code, notes, and snippets.

@mick001
Created August 29, 2015 21:12
The maths of Texas Hold ’em with R part 1. Full article at http://www.firsttimeprogrammer.blogspot.com/2014/07/the-math-of-texas-hold-em-with-r.html
# A deck of 52 cards (Jokers are excluded)
deck = c("A","A","A","A","K","K","K","K","Q","Q","Q","Q","J","J","J","J",10,10,10,10,9,9,9,9,8,8,8,8,7,7,7,7,6,6,6,6,5,5,5,5,4,4,4,4,3,3,3,3,2,2,2,2)
# This function simulates a hand at Texas Hold'em poker for 2 players and the dealer
hand <- function()
{
player1Hand <- sample(deck,2,F)
for(i in player1Hand)
{
# is.element(i,deck) checks if the element i is in the vector deck
# match gets the position of the i element in the vector deck and deck[-v] deletes the vth element of the vector deck
if(is.element(i,deck)
){
deck<-deck[-match(i,deck)]
}
}
player2Hand <- sample(deck,2,F)
for(i in player2Hand)
{
if(is.element(i,deck))
{
deck<-deck[-match(i,deck)]
}
}
# The flop
dealt_cards <- sample(deck,3,F)
for(i in dealt_cards)
{
if(is.element(i,deck))
{
deck<-deck[-match(i,deck)]
}
}
# The turn
second_dealt <- sample(deck,1,F)
for(i in second_dealt)
{
if(is.element(i,deck))
{
deck<-deck[-match(i,deck)]
dealt_cards = append(dealt_cards,second_dealt)
}
}
# The river
third_dealt <- sample(deck,1,F)
for(i in third_dealt)
{
if(is.element(i,deck))
{
deck<-deck[-match(i,deck)]
dealt_cards = append(dealt_cards,third_dealt)
}
}
# Eventually, a list of the results is returned by the function
results = list(player1Hand,player2Hand,dealt_cards)
return(results)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment