Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Last active June 26, 2018 20:48
Show Gist options
  • Save primaryobjects/02b804ecaddcad7410140600bf12020b to your computer and use it in GitHub Desktop.
Save primaryobjects/02b804ecaddcad7410140600bf12020b to your computer and use it in GitHub Desktop.
roll <- function(input) {
parts <- as.numeric(unlist(strsplit(input, 'd')))
sum(sample(1:parts[2], parts[1], replace=T))
}
input <- c('5d12', '6d4', '1d2', '1d8', '3d6', '4d20', '100d100')
result <- sapply(input, function(value) {
sum(roll(value))
})
print(data.frame(input=input, value=result))
# Generate a histogram plot to visualize the spread of dice values as random.
r <- '4d20'
x <- sapply(1:10000, function(i) { roll(r) })
df <- data.frame(index=seq_along(x), value=x)
hist(x, main=paste('Histogram of', r))
ggplot(data=df, aes(df$value)) +
geom_histogram(col="red", aes(fill=..count..)) +
scale_fill_gradient("Count", low = "blue", high = "purple") +
xlab('Roll') +
ylab('Frequency') +
ggtitle(paste('Histogram of', r))
input value
5d12 5d12 42
6d4 6d4 11
1d2 1d2 2
1d8 1d8 2
3d6 3d6 11
4d20 4d20 25
100d100 100d100 5215
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment