1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
// Copyright 2017 Kyle Mayes
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::iter;

use super::polynomial::{Polynomial};
use super::ratio::{Ratio};
use super::super::{Die, Dice, Fold, Reroll};

//================================================
// Macros
//================================================

// probabilities! ________________________________

macro_rules! probabilities {
    ($polynomial:expr, $dice:expr, $reroll:expr, $results:expr) => ({
        let polynomial = $polynomial;
        let dice = $dice;
        let exponent = if $reroll.is_some() { dice.0 * 2 } else { dice.0 };
        let permutations = ((dice.1).0 as i128).pow(exponent);
        let results = dice.results($results).enumerate();
        results.map(move |(i, r)| (r, Ratio::new(polynomial[i], permutations))).collect()
    });
}

//================================================
// Structs
//================================================

// Dice __________________________________________

impl Dice {
    //- Accessors --------------------------------

    /// Returns the smallest possible result of rolling this set of dice.
    pub fn minimum(&self, fold: Fold) -> i32 {
        match fold {
            Fold::DropMinimum | Fold::DropMaximum => self.0 as i32 - 1,
            Fold::Minimum | Fold::Maximum => 1,
            Fold::Sum => self.0 as i32,
        }
    }

    /// Returns the largest possible result of rolling this set of dice.
    pub fn maximum(&self, fold: Fold) -> i32 {
        match fold {
            Fold::DropMinimum | Fold::DropMaximum => ((self.0 - 1) * (self.1).0) as i32,
            Fold::Minimum | Fold::Maximum => (self.1).0 as i32,
            Fold::Sum => (self.0 * (self.1).0) as i32,
        }
    }

    /// Returns the average result of rolling this set of dice.
    pub fn average(&self, reroll: Option<Reroll>, fold: Fold) -> Ratio {
        if fold == Fold::Sum {
            Ratio::new(self.0 as i128, 1) * self.die().average(reroll)
        } else {
            let probabilities = self.probabilities(reroll, fold).into_iter();
            probabilities.fold(Ratio::zero(), |a, (r, p)| a + (Ratio::new(r as i128, 1) * p))
        }
    }

    /// Returns all the possible results of rolling this set of dice.
    pub fn results(&self, fold: Fold) -> impl Iterator<Item=i32> {
        self.minimum(fold)..(self.maximum(fold) + 1)
    }

    /// Returns the probabilities of all the possible results of rolling this set of dice.
    pub fn probabilities(&self, reroll: Option<Reroll>, fold: Fold) -> Vec<(i32, Ratio)> {
        match fold {
            Fold::DropMinimum => probabilities_drop_minimum(*self, reroll),
            Fold::DropMaximum => probabilities_drop_maximum(*self, reroll),
            Fold::Minimum => probabilities_minimum(*self, reroll),
            Fold::Maximum => probabilities_maximum(*self, reroll),
            Fold::Sum => probabilities(*self, reroll),
        }
    }
}

//================================================
// Functions
//================================================

fn repeat<T>(value: T, n: usize) -> impl Iterator<Item=T> where T: Copy {
    iter::repeat(value).take(n)
}

fn coefficients(die: Die, reroll: Option<Reroll>) -> Vec<i128> {
    if let Some(reroll) = reroll {
        let (low, high) = super::numerators(die, reroll);
        let mut coefficients = Vec::with_capacity(die.0 as usize);
        coefficients.extend(repeat(low, low as usize));
        coefficients.extend(repeat(high, die.0 as usize - low as usize));
        coefficients
    } else {
        vec![1; die.0 as usize]
    }
}

fn probabilities(dice: Dice, reroll: Option<Reroll>) -> Vec<(i32, Ratio)> {
    let polynomial = Polynomial::new(coefficients(dice.1, reroll)).pow(dice.0);
    probabilities!(polynomial, dice, reroll, Fold::Sum)
}

fn polynomials_drop_minimum(dice: Dice, reroll: Option<Reroll>) -> Vec<Polynomial> {
    let coefficients = coefficients(dice.1, reroll);
    dice.die().results().map(|r| {
        let zero = r as usize - 1;
        let coefficients = repeat(0, zero).chain(coefficients.iter().cloned().skip(zero));
        Polynomial::new(coefficients.collect()).pow(dice.0)
    }).collect()
}

fn polynomial_drop_minimum(dice: Dice, reroll: Option<Reroll>) -> Polynomial {
    let polynomials = polynomials_drop_minimum(dice, reroll);
    let mut polynomial = Polynomial::new(vec![0; polynomials.last().unwrap().size()]);
    for (k, left) in polynomials.iter().enumerate() {
        let mut summand = left.clone();
        if k + 1 < polynomials.len() {
            summand -= &polynomials[k + 1];
        }
        summand.reduce(k);
        polynomial += &summand;
    }
    polynomial
}

fn probabilities_drop_minimum(dice: Dice, reroll: Option<Reroll>) -> Vec<(i32, Ratio)> {
    let polynomial = polynomial_drop_minimum(dice, reroll);
    probabilities!(polynomial, dice, reroll, Fold::DropMinimum)
}

fn probabilities_minimum(dice: Dice, reroll: Option<Reroll>) -> Vec<(i32, Ratio)> {
    let sums = polynomials_drop_minimum(dice, reroll).iter().map(|p| p.sum()).collect::<Vec<_>>();
    let differences = sums.iter().enumerate().map(|(i, s)| {
        if i + 1 == sums.len() { *s } else { s - sums[i + 1] }
    }).collect::<Vec<_>>();
    probabilities!(differences, dice, reroll, Fold::Minimum)
}

fn polynomials_drop_maximum(dice: Dice, reroll: Option<Reroll>) -> Vec<Polynomial> {
    let coefficients = coefficients(dice.1, reroll);
    dice.die().results().map(|r| {
        let zeroes = repeat(0, ((dice.1).0 - r as u32) as usize);
        let coefficients = coefficients.iter().cloned().take(r as usize).chain(zeroes);
        Polynomial::new(coefficients.collect()).pow(dice.0)
    }).collect()
}

fn polynomial_drop_maximum(dice: Dice, reroll: Option<Reroll>) -> Polynomial {
    let polynomials = polynomials_drop_maximum(dice, reroll);
    let mut polynomial = Polynomial::new(vec![0; polynomials.last().unwrap().size()]);
    for (k, left) in polynomials.iter().enumerate() {
        let mut summand = left.clone();
        if k != 0 {
            summand -= &polynomials[k - 1];
        }
        summand.reduce(k);
        polynomial += &summand;
    }
    polynomial
}

fn probabilities_drop_maximum(dice: Dice, reroll: Option<Reroll>) -> Vec<(i32, Ratio)> {
    let polynomial = polynomial_drop_maximum(dice, reroll);
    probabilities!(polynomial, dice, reroll, Fold::DropMaximum)
}

fn probabilities_maximum(dice: Dice, reroll: Option<Reroll>) -> Vec<(i32, Ratio)> {
    let sums = polynomials_drop_maximum(dice, reroll).iter().map(|p| p.sum()).collect::<Vec<_>>();
    let differences = sums.iter().enumerate().map(|(i, s)| {
        if i == 0 { *s } else { s - sums[i - 1] }
    }).collect::<Vec<_>>();
    probabilities!(differences, dice, reroll, Fold::Maximum)
}