summaryrefslogtreecommitdiff
path: root/dice/src/main/java/bjc/dicelang/dicev2/ReduceDieMod.java
blob: 070c510cb9bfd4d212f1ddb302f5280be56dbd38 (plain)
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
package bjc.dicelang.dicev2;

import java.util.function.LongBinaryOperator;

/**
 * Die pool which performs a reduction.
 * 
 * @author Ben Culkin
 *
 */
public class ReduceDieMod extends Die {
	/**
	 * The die pool.
	 */
	public final Die[] dice;

	/**
	 * The reduction operation.
	 */
	public final LongBinaryOperator fold;
	
	/**
	 * The initial value for the reduction.
	 */
	public final long initial;

	/**
	 * Create a new reducing die pool.
	 * 
	 * @param fold The reduction operation.
	 * @param initial The initial value for the reduction.
	 * @param dice The die pool.
	 */
	public ReduceDieMod(LongBinaryOperator fold, long initial, Die... dice) {
		super();

		this.dice = dice;

		this.fold    = fold;
		this.initial = initial;
	}

	@Override
	public long[] roll() {
		return new long[] { rollSingle() };
	}

	@Override
	public long rollSingle() {
		long res = initial;

		for(Die die : dice) {
			for(long val : die.roll()) {
				res = fold.applyAsLong(res, val);
			}
		}

		return res;
	}

	@Override
	public boolean canOptimize() {
		for(Die die : dice) {
			if(!die.canOptimize()) return false;
		}

		return true;
	}

	@Override
	public long optimize() {
		long res = 0;

		for(Die die : dice) {
			res = fold.applyAsLong(res, die.optimize());
		}

		return res;
	}
}