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
// 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::collections::{HashMap, HashSet};

use super::ratio::{Ratio};
use super::super::{Binary, Expression};

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

// binary! _______________________________________

macro_rules! binary {
    ($left:expr, $right:expr, $operation:ident) =>  ({
        match ($left, $right) {
            (Some(left), Some(right)) => left.$operation(right),
            _ => None,
        }
    });
}

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

// Expression ____________________________________

impl Expression {
    //- Accessors --------------------------------

    /// Returns the smallest possible result of rolling this dice rolling expression.
    pub fn minimum(&self) -> Option<i32> {
        match *self {
            Expression::Binary(binary, ref left, ref right) => match binary {
                Binary::Add => binary!(left.minimum(), right.minimum(), checked_add),
                Binary::Divide => binary!(left.minimum(), right.maximum(), checked_div),
                Binary::Multiply => binary!(left.minimum(), right.minimum(), checked_mul),
                Binary::Subtract => binary!(left.minimum(), right.maximum(), checked_sub),
            },
            Expression::Constant(constant) => Some(constant as i32),
            Expression::Dice(dice, _, fold) => Some(dice.minimum(fold) as i32),
            Expression::Die(die, _) => Some(die.minimum() as i32),
        }
    }

    /// Returns the largest possible result of rolling this dice rolling expression.
    pub fn maximum(&self) -> Option<i32> {
        match *self {
            Expression::Binary(binary, ref left, ref right) => match binary {
                Binary::Add => binary!(left.maximum(), right.maximum(), checked_add),
                Binary::Divide => binary!(left.maximum(), right.minimum(), checked_div),
                Binary::Multiply => binary!(left.maximum(), right.maximum(), checked_mul),
                Binary::Subtract => binary!(left.maximum(), right.minimum(), checked_sub),
            },
            Expression::Constant(constant) => Some(constant as i32),
            Expression::Dice(dice, _, fold) => Some(dice.maximum(fold) as i32),
            Expression::Die(die, _) => Some(die.maximum() as i32),
        }
    }

    /// Returns the average result of rolling this dice rolling expression.
    pub fn average(&self) -> Option<Ratio> {
        match *self {
            Expression::Binary(binary, ref left, ref right) => match binary {
                Binary::Add => binary!(left.average(), right.average(), checked_add),
                Binary::Divide => {
                    let left = try_opt!(left.probabilities());
                    let right = try_opt!(right.probabilities());
                    let mut average = Ratio::zero();
                    for (lr, lp) in left {
                        for &(rr, rp) in &right {
                            average += Ratio::new((lr / rr) as i128, 1) * (lp * rp);
                        }
                    }
                    Some(average)
                },
                Binary::Multiply => binary!(left.average(), right.average(), checked_mul),
                Binary::Subtract => binary!(left.average(), right.average(), checked_sub),
            },
            Expression::Constant(constant) => Some(Ratio::new(constant as i128, 1)),
            Expression::Dice(dice, reroll, fold) => Some(dice.average(reroll, fold)),
            Expression::Die(die, reroll) => Some(die.average(reroll)),
        }
    }

    /// Returns all the possible results of rolling this dice rolling expression.
    pub fn results(&self) -> Option<Vec<i32>> {
        match *self {
            Expression::Binary(binary, ref left, ref right) => {
                let left = try_opt!(left.results());
                let right = try_opt!(right.results());
                let mut results = HashSet::new();
                for lr in left {
                    for rr in &right {
                        results.insert(try_opt!(binary.combine(lr, *rr)));
                    }
                }
                let mut results = results.into_iter().collect::<Vec<_>>();
                results.sort();
                Some(results)
            },
            Expression::Constant(constant) => Some(vec![constant as i32]),
            Expression::Dice(dice, _, fold) => Some(dice.results(fold).collect()),
            Expression::Die(die, _) => Some(die.results().collect()),
        }
    }

    /// Returns the probabilities of all the possible results of rolling this dice rolling expression.
    pub fn probabilities(&self) -> Option<Vec<(i32, Ratio)>> {
        match *self {
            Expression::Binary(binary, ref left, ref right) => {
                let left = try_opt!(left.probabilities());
                let right = try_opt!(right.probabilities());
                let mut probabilities = try_opt!(self.results()).into_iter().map(|r| {
                    (r, Ratio::zero())
                }).collect::<HashMap<_, _>>();
                for (lr, lp) in left {
                    for &(rr, rp) in &right {
                        let result = try_opt!(binary.combine(lr, rr));
                        *probabilities.get_mut(&result).unwrap() += lp * rp;
                    }
                }
                let mut probabilities = probabilities.into_iter().collect::<Vec<_>>();
                probabilities.sort();
                Some(probabilities)
            },
            Expression::Constant(constant) => Some(vec![(constant as i32, Ratio::new(1, 0))]),
            Expression::Dice(dice, reroll, fold) => Some(dice.probabilities(reroll, fold)),
            Expression::Die(die, reroll) => Some(die.probabilities(reroll)),
        }
    }
}