Created
July 30, 2022 22:22
-
-
Save nwstephens/a38ad28ec3bc29ffd115922c384afa00 to your computer and use it in GitHub Desktop.
Simulate the card game "War" with R
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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() |
Author
nwstephens
commented
Jul 30, 2022

Author
This simulation treats ties randomly
Author
If you simulate thousands of games the number of hands played averages to around 350 with a maximum in the thousands.
Author
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