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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
use itertools::Itertools;
use std::collections::HashMap;
use std::cmp::Ordering;
use crate::dice::*;
use crate::item_counter::ItemCounter;
#[cfg(test)]
mod tests;
#[derive(Eq, PartialEq, Clone, Hash)]
struct RollResultPossibility {
symbols: ItemCounter<DieSymbol>
}
impl RollResultPossibility {
pub fn new() -> RollResultPossibility {
RollResultPossibility {
symbols: ItemCounter::new()
}
}
pub fn add_symbols(&self, symbols: &[DieSymbol]) -> RollResultPossibility {
let mut symbol_count = self.clone().symbols;
for symbol in symbols {
symbol_count.add(symbol);
}
RollResultPossibility { symbols: symbol_count }
}
pub fn total_count(&self) -> usize {
self.symbols.total_count()
}
}
/// Represents the type of targets for a given roll
#[derive(Copy, Clone, PartialEq, Eq)]
enum RollTargetTypes {
Exactly,
AtLeast,
AtMost
}
#[derive(Copy, Clone, PartialEq, Eq)]
/// Represents the target for a given roll
pub struct RollTarget<'a> {
target_type: RollTargetTypes,
amount: usize,
symbols: &'a [DieSymbol]
}
impl<'a> RollTarget<'a> {
/// Returns an instance of a target that is exactly N of provided symbols
pub fn exactly_n_of(n: usize, symbols: &'a [DieSymbol]) -> RollTarget {
RollTarget {
target_type: RollTargetTypes::Exactly,
amount: n,
symbols
}
}
/// Returns an instance of a target that is at least N of provided symbols
pub fn at_least_n_of(n: usize, symbols: &'a [DieSymbol]) -> RollTarget {
RollTarget {
target_type: RollTargetTypes::AtLeast,
amount: n,
symbols
}
}
/// Returns an instance of a target that is at most N of provided symbols
pub fn at_most_n_of(n: usize, symbols: &'a [DieSymbol]) -> RollTarget {
RollTarget {
target_type: RollTargetTypes::AtMost,
amount: n,
symbols
}
}
}
#[derive(Copy, Clone, PartialEq, Eq)]
enum RollCollectionTypes {
CollectAll,
TakeHighestN(usize),
TakeLowestN(usize),
RemoveHighestN(usize),
RemoveLowestN(usize)
}
#[derive(Copy, Clone, PartialEq, Eq)]
/// Defines the policy used to collect dice after a roll based on [`DieSymbol`](crate::dice::DieSymbol) occurrences
pub struct RollCollectionPolicy<'a> {
coll_type: RollCollectionTypes,
symbols: &'a [DieSymbol]
}
impl<'a> RollCollectionPolicy<'a> {
/// Policy for collecting all dice in the roll
pub fn collect_all(symbols: &'a [DieSymbol]) -> RollCollectionPolicy {
RollCollectionPolicy {
coll_type: RollCollectionTypes::CollectAll,
symbols
}
}
/// Policy for taking the highest N dice, ordering by number of matching symbols
pub fn take_highest_n_of(n:usize, symbols: &'a [DieSymbol]) -> RollCollectionPolicy {
RollCollectionPolicy {
coll_type: RollCollectionTypes::TakeHighestN(n),
symbols
}
}
/// Policy for taking the lowest N dice, ordering by number of matching symbols
pub fn take_lowest_n_of(n:usize, symbols: &'a [DieSymbol]) -> RollCollectionPolicy {
RollCollectionPolicy {
coll_type: RollCollectionTypes::TakeLowestN(n),
symbols
}
}
/// Policy for removing the highest N dice and collecting the rest, ordering by number of matching symbols
pub fn remove_highest_n_of(n:usize, symbols: &'a [DieSymbol]) -> RollCollectionPolicy {
RollCollectionPolicy {
coll_type: RollCollectionTypes::RemoveHighestN(n),
symbols
}
}
/// Policy for removing the lowest N dice and collecting the rest, ordering by number of matching symbols
pub fn remove_lowest_n_of(n:usize, symbols: &'a [DieSymbol]) -> RollCollectionPolicy {
RollCollectionPolicy {
coll_type: RollCollectionTypes::RemoveLowestN(n),
symbols
}
}
}
/// Tracks the probabilities of a roll of one or more dice
pub struct RollProbabilities {
occurrences: HashMap<RollResultPossibility, usize>,
total: usize
}
impl RollProbabilities {
fn collect_symbols(roll: &[&DieSide], policy: &RollCollectionPolicy) -> Vec<DieSymbol> {
let mut filtered_sides: Vec<Vec<DieSymbol>> =
roll.iter()
.map(|x|
x.symbols().iter()
.filter(|y| policy.symbols.contains(y))
.cloned().collect())
.collect();
filtered_sides.sort_by(|x,y| x.len().cmp(&y.len()));
filtered_sides.reverse();
let sides_len = filtered_sides.len();
match policy.coll_type {
RollCollectionTypes::CollectAll =>
filtered_sides.iter()
.flatten().cloned().collect(),
RollCollectionTypes::TakeHighestN(n) =>
filtered_sides.iter().take(n)
.flatten().cloned().collect(),
RollCollectionTypes::TakeLowestN(n) =>
filtered_sides.iter().skip(sides_len - n)
.flatten().cloned().collect(),
RollCollectionTypes::RemoveHighestN(n) =>
filtered_sides.iter().skip(n)
.flatten().cloned().collect(),
RollCollectionTypes::RemoveLowestN(n) =>
filtered_sides.iter().take(sides_len - n)
.flatten().cloned().collect()
}
}
/// Creates a new instance of [`RollProbabilities`](crate::rolls::RollProbabilities) based on the provided collection of [`Dice`](crate::dice::Die).
/// Die sides are collected based on the provided [`RollCollectionPolicy`](crate::rolls::RollCollectionPolicy).
/// Returns `Err` if provided slice contains no elements, else returns `Ok`.
///
/// # Example
/// ```rust
/// # use std::error::Error;
/// # use art_dice::dice::{DieSymbol, DieSide, Die};
/// # use art_dice::dice::standard;
/// # use art_dice::rolls::{RollTarget, RollProbabilities, RollCollectionPolicy};
/// # fn main() -> Result<(), String> {
/// let symbols = vec![ standard::pip() ] ;
/// let policy = RollCollectionPolicy::collect_all(&symbols);
/// let dice = vec![standard::d4(), standard::d4()];
///
/// let two_d4s = RollProbabilities::new(&dice, &policy)?;
/// # Ok(())
/// # }
/// ```
pub fn new(dice: &[Die], policy: &RollCollectionPolicy) -> Result<RollProbabilities, String> {
if dice.len() == 0 {
return Err("must include at least one die".to_string());
}
let mut occur = HashMap::new();
for roll in dice.into_iter()
.map(|x| x.sides())
.multi_cartesian_product() {
let collected = Self::collect_symbols(&roll, policy);
let new_poss =
RollResultPossibility::new()
.add_symbols(&collected);
if occur.contains_key(&new_poss) {
occur.get_mut(&new_poss).map(|x| *x += 1);
} else {
occur.insert(new_poss, 1);
}
}
let total = occur.values().sum();
Ok(RollProbabilities {
occurrences: occur,
total: total
})
}
/// Retrieves the probability of the roll achieving the [`RollTarget`](crate::rolls::RollTarget).
/// Note that the roll's [`DieSymbols`](crate::dice::DieSymbol) will have been filtered down based
/// on the [`RollCollectionPolicy`](crate::rolls::RollCollectionPolicy) used to generate the probability
///
/// # Examples
/// ```rust
/// # use std::error::Error;
/// # use art_dice::dice::{DieSymbol, DieSide, Die};
/// # use art_dice::dice::standard;
/// # use art_dice::rolls::{RollTarget, RollProbabilities, RollCollectionPolicy};
/// # fn main() -> Result<(), String> {
/// let dice = vec![standard::d4(), standard::d4()];
/// let symbols = vec![ standard::pip() ];
/// let policy = RollCollectionPolicy::collect_all(&symbols);
/// let two_d4s = RollProbabilities::new(&dice, &policy)?;
///
/// let exactly_3 = two_d4s.get_odds(RollTarget::exactly_n_of(3, &symbols));
/// let at_least_6 = two_d4s.get_odds(RollTarget::at_least_n_of(6, &symbols));
/// let at_most_5 = two_d4s.get_odds(RollTarget::at_most_n_of(5, &symbols));
///
/// assert_eq!(exactly_3, 0.125);
/// assert_eq!(at_least_6, 0.375);
/// assert_eq!(at_most_5, 0.625);
/// # Ok(())
/// # }
/// ```
pub fn get_odds(&self, target: RollTarget) -> f64 {
if self.total == 0 {
return 0.0;
}
let mut total_occurrences = 0;
for poss in self.occurrences.keys() {
let mut count: usize = 0;
for symbol in target.symbols {
count += poss.symbols.get_count(&symbol);
}
let cond = match target.target_type {
RollTargetTypes::Exactly => count == target.amount,
RollTargetTypes::AtLeast => count >= target.amount,
RollTargetTypes::AtMost => count <= target.amount
};
if cond {
total_occurrences += self.occurrences[poss];
}
}
return (total_occurrences as f64) / (self.total as f64);
}
/// Compares the results of one roll against another, returning a new [`RollCompareResult`](crate::rolls::RollCompareResult)
///
/// # Example
/// ```rust
/// # use std::error::Error;
/// # use art_dice::rolls::RollCompareResult;
/// # use art_dice::dice::{DieSymbol, DieSide, Die};
/// # use art_dice::dice::standard;
/// # use art_dice::rolls::{RollTarget, RollProbabilities, RollCollectionPolicy};
/// # fn main() -> Result<(), String> {
/// let symbols = vec![standard::pip()];
/// let d8_pool = vec![standard::d8()];
/// let d4_pool = vec![standard::d4()];
/// let policy = RollCollectionPolicy::collect_all(&symbols);
/// let d8_result = RollProbabilities::new(&d8_pool, &policy)?;
/// let d4_result = RollProbabilities::new(&d4_pool, &policy)?;
///
/// let compare = d8_result.roll_against(&d4_result);
///
/// assert_eq!(compare.win_odds(), 0.6875);
/// assert_eq!(compare.tie_odds(), 0.125);
/// assert_eq!(compare.loss_odds(), 0.1875);
/// # Ok(())
/// # }
/// ```
pub fn roll_against(&self, other: &Self) -> RollCompareResult {
let (wins,ties,losses) =
self.occurrences.iter()
.cartesian_product(other.occurrences.iter())
.map(|(this_poss, other_poss)| {
let this_val = this_poss.0.total_count();
let other_val = other_poss.0.total_count();
let occurrences = this_poss.1 * other_poss.1;
match this_val.cmp(&other_val) {
Ordering::Greater => (occurrences, 0, 0),
Ordering::Equal => (0, occurrences, 0),
Ordering::Less => (0, 0, occurrences)
}})
.fold((0, 0, 0), |(x, y, z), (i, j ,k)| (x+i, y+j, z+k));
return RollCompareResult::new(wins, ties, losses);
}
}
/// Represents the probabilities of a roll against another pool of dice
pub struct RollCompareResult {
wins: usize,
ties: usize,
losses: usize,
total: usize
}
impl RollCompareResult {
/// Creates a new instance of [`RollCompareResult`](crate::rolls::RollCompareResult)
///
/// # Example
/// ```rust
/// # use std::error::Error;
/// # use art_dice::rolls::RollCompareResult;
/// # fn main() -> Result<(), String> {
/// let compare = RollCompareResult::new(3, 1, 4);
/// # Ok(())
/// # }
/// ```
pub fn new(wins: usize, ties: usize, losses: usize) -> RollCompareResult {
let total = wins + ties + losses;
RollCompareResult {
wins,
ties,
losses,
total
}
}
/// In a roll of [`a.roll_against(&b)`](crate::rolls::RollProbabilities::roll_against), returns the probability, as a decimal, of dice roll `a`'s value exceeding dice roll `b`'s value.
/// Returns `0.0` if the struct is empty.
///
/// # Example
/// ```rust
/// # use std::error::Error;
/// # use art_dice::rolls::RollCompareResult;
/// # use art_dice::dice::{DieSymbol, DieSide, Die};
/// # use art_dice::dice::standard;
/// # use art_dice::rolls::{RollTarget, RollProbabilities, RollCollectionPolicy};
/// # fn main() -> Result<(), String> {
/// # let symbols = vec![standard::pip()];
/// # let d8_pool = vec![standard::d8()];
/// # let d4_pool = vec![standard::d4()];
/// # let policy = RollCollectionPolicy::collect_all(&symbols);
/// # let d8_result = RollProbabilities::new(&d8_pool, &policy)?;
/// # let d4_result = RollProbabilities::new(&d4_pool, &policy)?;
/// let compare = d8_result.roll_against(&d4_result);
///
/// assert_eq!(compare.win_odds(), 0.6875);
/// # Ok(())
/// # }
/// ```
pub fn win_odds(&self) -> f64 {
if self.total == 0 {
return 0.0
}
(self.wins as f64) / (self.total as f64)
}
/// In a roll of [`a.roll_against(&b)`](crate::rolls::RollProbabilities::roll_against), returns the probability, as a decimal, of dice roll `a`'s value matching dice roll `b`'s value.
/// Returns `0.0` if the struct is empty.
///
/// # Example
/// ```rust
/// # use std::error::Error;
/// # use art_dice::rolls::RollCompareResult;
/// # use art_dice::dice::{DieSymbol, DieSide, Die};
/// # use art_dice::dice::standard;
/// # use art_dice::rolls::{RollTarget, RollProbabilities, RollCollectionPolicy};
/// # fn main() -> Result<(), String> {
/// # let symbols = vec![standard::pip()];
/// # let d8_pool = vec![standard::d8()];
/// # let d4_pool = vec![standard::d4()];
/// # let policy = RollCollectionPolicy::collect_all(&symbols);
/// # let d8_result = RollProbabilities::new(&d8_pool, &policy)?;
/// # let d4_result = RollProbabilities::new(&d4_pool, &policy)?;
/// let compare = d8_result.roll_against(&d4_result);
///
/// assert_eq!(compare.tie_odds(), 0.125);
/// # Ok(())
/// # }
/// ```
pub fn tie_odds(&self) -> f64 {
if self.total == 0 {
return 0.0
}
(self.ties as f64) / (self.total as f64)
}
/// In a roll of [`a.roll_against(&b)`](crate::rolls::RollProbabilities::roll_against), returns the probability, as a decimal, of dice roll `b`'s value exceeding dice roll `a`'s value.
/// Returns `0.0` if the struct is empty.
///
/// # Example
/// ```rust
/// # use std::error::Error;
/// # use art_dice::rolls::RollCompareResult;
/// # use art_dice::dice::{DieSymbol, DieSide, Die};
/// # use art_dice::dice::standard;
/// # use art_dice::rolls::{RollTarget, RollProbabilities, RollCollectionPolicy};
/// # fn main() -> Result<(), String> {
/// # let symbols = vec![standard::pip()];
/// # let d8_pool = vec![standard::d8()];
/// # let d4_pool = vec![standard::d4()];
/// # let policy = RollCollectionPolicy::collect_all(&symbols);
/// # let d8_result = RollProbabilities::new(&d8_pool, &policy)?;
/// # let d4_result = RollProbabilities::new(&d4_pool, &policy)?;
/// let compare = d8_result.roll_against(&d4_result);
///
/// assert_eq!(compare.loss_odds(), 0.1875);
/// # Ok(())
/// # }
/// ```
pub fn loss_odds(&self) -> f64 {
if self.total == 0 {
return 0.0
}
(self.losses as f64) / (self.total as f64)
}
}