From c5145da9d7ac09b4aa15ac1e5652b841a6598072 Mon Sep 17 00:00:00 2001 From: "Benjamin J. Culkin" Date: Mon, 11 Sep 2017 12:12:10 -0300 Subject: Add converge combinator Adds a function that creates a function that iterates an operator until it either converges or exceeds a defined number of iterations. --- .../main/java/bjc/utils/funcutils/FuncUtils.java | 27 ++++++++++++++++++++++ 1 file changed, 27 insertions(+) (limited to 'BJC-Utils2/src/main/java/bjc/utils') diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/FuncUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/FuncUtils.java index 0d1a688..cd1bcc9 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/FuncUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/FuncUtils.java @@ -45,4 +45,31 @@ public class FuncUtils { cons.accept(i); } } + + /** + * Return an operator that executes until it converges. + * + * @param op + * The operator to execute. + * @param maxTries + * The maximum amount of times to apply the function in an + * attempt to cause it to converge. + */ + public static UnaryOperator converge(final UnaryOperator op, final int maxTries) { + return (val) -> { + T newVal = op.apply(val); + T oldVal; + + int tries = 0; + + do { + oldVal = newVal; + newVal = op.apply(newVal); + + tries += 1; + } while(!newVal.equals(oldVal) && tries < maxTries); + + return newVal; + }; + } } -- cgit v1.2.3