From 4e042bd0eb0859175d3215fd4907176d57555b6c Mon Sep 17 00:00:00 2001 From: Danila Fedorin Date: Wed, 9 Aug 2017 12:34:02 -0700 Subject: [PATCH] Implement two combinatorics operators. --- .../nwapw/abacus/plugin/StandardPlugin.java | 44 +++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/src/main/java/org/nwapw/abacus/plugin/StandardPlugin.java b/src/main/java/org/nwapw/abacus/plugin/StandardPlugin.java index fdd3674..7d4fa3b 100755 --- a/src/main/java/org/nwapw/abacus/plugin/StandardPlugin.java +++ b/src/main/java/org/nwapw/abacus/plugin/StandardPlugin.java @@ -136,6 +136,47 @@ public class StandardPlugin extends Plugin { }*/ } }); + /** + * The permutation operator. + */ + public static final Operator OP_NPR = new Operator(OperatorAssociativity.RIGHT, OperatorType.BINARY_INFIX, 0, new Function() { + @Override + protected boolean matchesParams(NumberInterface[] params) { + return params.length == 2 && params[0].fractionalPart().signum() == 0 + && params[1].fractionalPart().signum() == 0; + } + + @Override + protected NumberInterface applyInternal(NumberInterface[] params) { + if(params[0].compareTo(params[1]) < 0 || + params[0].signum() < 0 || + (params[0].signum() == 0 && params[1].signum() != 0)) return fromInt(params[0].getClass(), 0); + NumberInterface total = fromInt(params[0].getClass(), 1); + NumberInterface multiplyBy = params[0]; + NumberInterface remainingMultiplications = params[1]; + while(remainingMultiplications.signum() > 0){ + total = total.multiply(multiplyBy); + remainingMultiplications = remainingMultiplications.subtract(fromInt(params[0].getClass(), 1)); + multiplyBy = multiplyBy.subtract(fromInt(params[0].getClass(), 1)); + } + return total; + } + }); + /** + * The combination operator. + */ + public static final Operator OP_NCR = new Operator(OperatorAssociativity.RIGHT, OperatorType.BINARY_INFIX, 0, new Function() { + @Override + protected boolean matchesParams(NumberInterface[] params) { + return params.length == 2 && params[0].fractionalPart().signum() == 0 + && params[1].fractionalPart().signum() == 0; + } + + @Override + protected NumberInterface applyInternal(NumberInterface[] params) { + return OP_NPR.getFunction().apply(params).divide(OP_FACTORIAL.getFunction().apply(params[1])); + } + }); /** * The absolute value function, abs(-3) = 3 */ @@ -575,6 +616,9 @@ public class StandardPlugin extends Plugin { registerOperator("^", OP_CARET); registerOperator("!", OP_FACTORIAL); + registerOperator("npr", OP_NPR); + registerOperator("ncr", OP_NCR); + registerFunction("abs", FUNCTION_ABS); registerFunction("exp", FUNCTION_EXP); registerFunction("ln", FUNCTION_LN);