DndDice/R/internal_functions.R

70 lines
1.6 KiB
R
Raw Normal View History

2019-03-19 03:56:07 +00:00
getProbabilitiy <- function(x, numbers){
positions = match(numbers, x$numbers)
probs = x$probs[positions]
probs[is.na(probs)] = 0
return(probs)
}
sumTwoDie <- function(x, y){
range_z_min = min(x$numbers) + min(y$numbers)
range_z_max = max(x$numbers) + max(y$numbers)
z_numbers = c()
probabilities = c()
for(num in range_z_min:range_z_max){
prob_num = sum(x$probs * getProbabilitiy(y, num - x$numbers))
if(prob_num > 0){
z_numbers = c(z_numbers, num)
probabilities = c(probabilities, prob_num)
}
}
z = makeDie(z_numbers, probabilities)
return(z)
}
# comparerFun(x, y); which both x & y as Die, or one of them as numeric
compareDie <- function(x, y, comparerFun){
if(class(x) == "Die" & class(y) == "Die"){
jointProbs = expand.grid(x$probs, y$probs)
jointProbs = jointProbs[,1]*jointProbs[,2]
jointNumbers = expand.grid(x$numbers, y$numbers)
matchResults = comparerFun(jointNumbers[,1], jointNumbers[,2])
probTrue = sum(jointProbs[matchResults])
z = makeDie(c(F,T), probs=c(1-probTrue, probTrue))
return(z)
}
if(class(x) %in% c("numeric", "integer")){
die = y
constant = x
xNumbers = constant
yNumbers = die$numbers
} else if(class(y) %in% c("numeric", "integer")){
die = x
constant = y
xNumbers = die$numbers
yNumbers = constant
} else{
stop("Can only compare two die or a die and a number")
}
if(length(constant) != 1){
stop("Length of constant must be 1")
}
matchResults = comparerFun(xNumbers, yNumbers)
probTrue = sum(die$probs[matchResults])
z = makeDie(c(F,T), probs=c(1-probTrue, probTrue))
}