blob: 3be56e4eedd4e4dff47b68b199cdd90f753a482e (
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
|
package bjc.utils.dice;
import java.util.Stack;
import bjc.utils.funcdata.FunctionalList;
import bjc.utils.funcdata.FunctionalStringTokenizer;
import bjc.utils.parserutils.ShuntingYard;
public class DiceExpressionParser {
public DiceExpression parse(String exp) {
FunctionalStringTokenizer fst = new FunctionalStringTokenizer(exp);
ShuntingYard<String> yard = new ShuntingYard<>();
FunctionalList<String> ls = yard.postfix(fst.toList(s -> s),
s -> s);
Stack<DiceExpression> dexps = new Stack<>();
ls.forEach((tok) -> {
if (tok.contains("d")) {
dexps.push(Dice.fromString(tok));
} else {
try {
dexps.push(new ScalarDie(Integer.parseInt(tok)));
} catch (NumberFormatException nfex) {
DiceExpression l = dexps.pop();
DiceExpression r = dexps.pop();
switch (tok) {
case "+":
dexps.push(new CompoundDiceExpression(l, r,
DiceExpressionType.ADD));
break;
case "-":
dexps.push(new CompoundDiceExpression(l, r,
DiceExpressionType.SUBTRACT));
break;
case "*":
dexps.push(new CompoundDiceExpression(l, r,
DiceExpressionType.MULTIPLY));
break;
case "/":
dexps.push(new CompoundDiceExpression(l, r,
DiceExpressionType.DIVIDE));
break;
default:
throw new IllegalStateException("Detected invalid operator " + tok);
}
}
}
});
return dexps.pop();
}
}
|