Skip to content

Instantly share code, notes, and snippets.

@coryhofmann
Created February 26, 2017 22:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coryhofmann/42da61364b4cb72919d4ca680b6a34db to your computer and use it in GitHub Desktop.
Save coryhofmann/42da61364b4cb72919d4ca680b6a34db to your computer and use it in GitHub Desktop.
#Yahtzee.R
#By Cory Hofmann
#Last Updated: 2/26/2017
#
#This code will simulate 3 rolls of 5 dice, trying to get a Yahtzee.
#Will determine odds of achieving Yahtzee in 1, 2, or 3 rolls.
#Also, to see best hand remaining if attempted and failed.
#Code is set-up to run 1,000,000 times to determine probabilities.
#
#Outputs:
#yahtzee -> # of Yahtzees in (1 Roll, 2 Roll, 3 Rolls)
#score -> Instances # of matching die (1, 2, 3, 4, 5)
remove(list=ls())
total <- 1000000 #Desired number of games to simulate
score <- rep(0,total)
yahtzee <- c(0, 0, 0)
for (j in 1:total){
###Roll 1
roll <- sample(1:6, 5, replace = T)
highest <- 0
for (i in c(1:6)){
if (sum(roll == i) > highest){
count <- sum(roll == i)
die <- i
highest <- sum(roll == i)
}
}
if (count == 5){
yahtzee[1] = yahtzee[1] + 1
score[j] <- 5
next
}
###Roll 2
roll2 <- sample(1:6, 5-count, replace = T)
count2 <- count + sum(roll2 == die)
if (count2 == 5){
yahtzee[2] = yahtzee[2] + 1
score[j] <- 5
next
}
#If Roll 2 was 'better' than Roll 1, Reassign
for (k in c(1:6)){
if (sum(roll2 == k) > count2){
count2 <- sum(roll2 == k)
die <- k #Reassign
}
}
###Roll 3
roll3 <- sample(1:6, 5-count2, replace = T)
count3 <- count2 + sum(roll3 == die)
#If Roll 3 was 'better' than Roll 2
for (l in c(1:6)){
if (sum(roll3 == l) > count3){
count3 <- sum(roll3 == l)
die <- l #Reassign
}
}
if (count3 == 5){
yahtzee[3] = yahtzee[3] + 1
score[j] <- 5
}else{
score[j] <- count3 #Highest multiple
}
}
#Output
#
#Yahtzee in 1, 2, 3 = .0745%; 1.1668%; 3.3620%;
#Total = 4.6033%
#
#Best Score:
#1: 0.0783%; 2: 25.6249%; 3: 45.2652%; 4: 24.4283%; 5: 4.6033%
#
#For Reference, Exact Probabilities:
#Yahtzee in 1, 2, 3 = .077%; 1.186%; 3.34%;
#Total = 4.603%
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment