Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add R tab to randomness test design (Yahtzee) #212

Merged
merged 1 commit into from
Mar 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions content/code/R/yahtzee.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#' Roll a fair die num_dice times.
#' Collect as many of the same dice side as possible.
#'
#' @return A vector of die throw results
roll_dice <- function(num_dice) {
ceiling(runif(num_dice, 0, 6))
}

#' Play yahtzee with 5 6-sided dice and 3 throws.
#' Collect as many of the same dice side as possible.
#'
#' @return The number of same sides
yahtzee <- function() {
res <- roll_dice(5)
most_common_side <- as.numeric(names(table(res)[which.max(table(res))]))[1]
how_often <- as.vector(table(res)[which.max(table(res))])[1]

# we keep the most common side
target_side <- most_common_side
num_same_sides <- how_often
if (num_same_sides == 5) {
return(5)
}

# second and third throw
for (i in 2:3) {
throw <- roll_dice(5 - num_same_sides)
num_same_sides <- num_same_sides + sum(throw == target_side)

if (num_same_sides == 5) {
return(5)
}
}
return(num_same_sides)
}
18 changes: 18 additions & 0 deletions content/code/R/yahtzee_sol.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
if (!require(testthat)) install.packages(testthat)

test_that("dice is working", {
set.seed(42)
expect_equal(roll_dice(5), c(6, 6, 2, 5, 4))
expect_equal(roll_dice(5), c(4, 5, 1, 4, 5))
expect_equal(roll_dice(5), c(3, 5, 6, 2, 3))
})


test_that("yahtzee is working", {
n_games <- 1e6 #could be very slow, when in doubt change to 1e4

n_winning <- sum(replicate(n_games, yahtzee()) == 5)
res <- (n_winning / n_games)
expected <- 0.046
expect_lt(abs(res - expected), 0.003)
})
14 changes: 14 additions & 0 deletions content/test-design.md
Original file line number Diff line number Diff line change
Expand Up @@ -607,6 +607,13 @@ many strategies exist:
```
````

````{group-tab} R

```{literalinclude} code/R/yahtzee.R
:language: R
```
````

````{group-tab} Julia

```{literalinclude} code/julia/yahtzee.jl
Expand All @@ -633,6 +640,13 @@ many strategies exist:
```
````

````{group-tab} R

```{literalinclude} code/R/yahtzee_sol.R
:language: R
```
````

````{group-tab} Julia

```{literalinclude} code/julia/yahtzee_sol.jl
Expand Down
Loading