Skip to content

Instantly share code, notes, and snippets.

@nwstephens
Created July 30, 2022 22:22
Show Gist options
  • Select an option

  • Save nwstephens/a38ad28ec3bc29ffd115922c384afa00 to your computer and use it in GitHub Desktop.

Select an option

Save nwstephens/a38ad28ec3bc29ffd115922c384afa00 to your computer and use it in GitHub Desktop.
Simulate the card game "War" with R
g <- function(){
deck = rep(1:13, each=4)
deal <- sample(length(deck))
p1 <- deck[deal[1:26]]
p2 <- deck[deal[27:52]]
hands <- 1
wins <- matrix(NA, 0, 4)
while(length(p1) > 0 & length(p2) > 0){
hands <- hands + 1
wins <- rbind(wins, c(p1[1], p2[1], length(p1), length(p2)))
if(p1[1] == p2[1]) player <- rbinom(1,1,0.5) else player <- p1[1] > p2[1]
if(player) {p1 <- c(p1[-1], p1[1], p2[1]); p2 <- p2[-1]} else
{p2 <- c(p2[-1], p2[1], p1[1]); p1 <- p1[-1]}
}
plot(wins[,3],type='l',ylim=c(0,52))
lines(wins[,4],col='tomato')
return(hands)
}
g()
@nwstephens
Copy link
Author

image

@nwstephens
Copy link
Author

This simulation treats ties randomly

@nwstephens
Copy link
Author

If you simulate thousands of games the number of hands played averages to around 350 with a maximum in the thousands.

@nwstephens
Copy link
Author

nwstephens commented Jul 30, 2022

Here's a condensed version without the plot:

g <- function(deck = sample(rep(1:13, each=4))){
  p1 <- deck[deal[1:26]]
  p2 <- deck[deal[27:52]]
  while(length(p1) > 0 & length(p2) > 0){
    if(p1[1] == p2[1]) player <- rbinom(1,1,0.5) else player <- p1[1] > p2[1]
    if(player) {p1 <- c(p1[-1], p1[1], p2[1]); p2 <- p2[-1]} else
    {p2 <- c(p2[-1], p2[1], p1[1]); p1 <- p1[-1]}
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment